Detailed summary of JavaScript BOM and DOM and their compatible operations

Posted by matte on Wed, 17 Nov 2021 05:35:10 +0100

BOM (browser object model)

All browsers support window Object that represents the browser window.
All js Global objects, functions, and variables automatically become window Object.
The global variable is window Object.
The global function is window Object.
be based on html dom of document Also window One of the properties of the object.
 window.document.getElementById("header");
 document.getElementById("header");

1. Get browser c window size through window

Internal height of browser window (excluding scroll bar, menu bar and toolbar)

window.innerHeight
window.innerWidth

The window s applicable to Internet Explorer 8, 7, 6 and 5 browsers are as follows:

document.documentElement.clientHeight
document.documentElement.clientWidth

Get browser width and height for compatibility scheme`

var width=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth
var height=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight

2. screen gets the computer screen size

Property returns the width / height of the visitor's screen, in pixels, minus interface features, such as the window taskbar.

screen.availWidth
screen.availHeight

3. window open close window

Open: window.open()
Close: window.close()

<script type="text/javascript">
    var newWindows;
    function newWindow() {
        newWindows = window.open("https://www.baidu.com/","baidu");
    }
    function closeWindow() {
        newWindows.close();
    }
</script>

4. Browser events

namedescribe
window.onloadBrowser load event
window.onscrollBrowser scroll monitor
window.onresizeBrowser zoom monitor
window.openOpen event
window.closeclose

5. location

Get the current web page address. The browser can direct to a new web page (the current page is open) without writing window This prefix     
namedescribe
location.herfCurrent url
location.hostnameHost domain name
location.pathnameCurrent page path and file name
location.portport
location.protocolProtocol (http/https)
location.assignLoad new document
location.searchurl parameter
console.log(location.href);
console.log(location.hostname);
console.log(location.pathname);
console.log(location.port);
console.log(location.protocol);

6. history

Browser history, you can not write the prefix window

namedescribe
history.lengthfrequency
history.backprevious page
history.forwardnext page
history.goIn parentheses, set the number and sign, + number of times to jump to the next value, - number of times to jump to the previous value, calculation of times: End Page - start page, wrong jump times, no execution effect

window.history.back();

7. navigator obtains browser related information

window.navigator

namedescribe
navagator.userAgentModel, kernel, version, platform
navagator.appVersionBrowser version information
navagator.appNameBrowser name
navagator.platformoperating system
navagator.geolocationThe location information includes longitude and latitude
export function GetCurrentBrowser() {
    var agent = navigator.userAgent.toLowerCase();
    var regStr_ie = /msie [\d.]+;/gi;
    var regStr_ff = /firefox\/[\d.]+/gi
    var regStr_chrome = /chrome\/[\d.]+/gi;
    var regStr_saf = /safari\/[\d.]+/gi;
    //Below IE11
    if (agent.indexOf("msie") > 0) {
        return agent.match(regStr_ie);
    }
    //MSIE field is not included in IE11 version
    if (agent.indexOf("trident") > 0 && agent.indexOf("rv") > 0) {
        return "IE " + agent.match(/rv:(\d+\.\d+)/)[1];
    }
    //firefox
    if (agent.indexOf("firefox") > 0) {
        return agent.match(regStr_ff);
    }
    //Chrome
    if (agent.indexOf("chrome") > 0) {
        return agent.match(regStr_chrome);
    }
    //Safari
    if (agent.indexOf("safari") > 0 && agent.indexOf("chrome") < 0) {
        return agent.match(regStr_saf);
    }
}

// get os
export function GetOs() {
    let userAgent = navigator.userAgent.toLocaleLowerCase() //Tolocalelovercase() converts letters to lowercase
    let wins = [
        {
            sys: 'windows nt 5.0',
            alias: 'windows 2000',
            name: 'Win2000'
        },
        {
            sys: 'windows nt 5.1',
            alias: 'windows xp',
            name: 'WinXP'
        },
        {
            sys: 'windows nt 5.2',
            alias: 'windows 2003',
            name: 'Win2003'
        },
        {
            sys: 'windows nt 6.0',
            alias: 'Windows Vista',
            name: 'WinVista'
        },
        {
            sys: 'windows nt 6.1',
            alias: 'Windows 7',
            name: 'Win7'
        },
        {
            sys: 'windows nt 6.2',
            alias: 'Windows 8',
            name: 'Win8'
        },
        {
            sys: 'windows nt 10.0',
            alias: 'Windows 10',
            name: 'Win10'
        },
    ]
    for (let win of wins) {
        if (userAgent.indexOf(win.sys) > -1 || userAgent.indexOf(win.alias) > -1) {
            return win.name
        }
    }
}
export function getEdition() {
    var userAgent = navigator.userAgent.toLocaleLowerCase()
    if (userAgent.indexOf("win64") > -1 || userAgent.indexOf("wow64") > -1) {
        return '64 position'
    } else {
        return '32 position'
    }
}
export function IsPC() {
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
        "SymbianOS", "Windows Phone",
        "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}
//Get url parameter return object
export function GetRequest() {
    var url = location.search; //Gets the string after the "?" character in the url
    var theRequest = {}
    let strs = []
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}
export const browser = {
    versions: (function() {
        let u = navigator.userAgent
            // let app = navigator.appVersion
        return {
            trident: u.indexOf('Trident') > -1, // IE kernel
            presto: u.indexOf('Presto') > -1, // opera kernel
            webKit: u.indexOf('AppleWebKit') > -1, // Apple, Google kernel
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // Firefox kernel
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), // Is it a mobile terminal
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios terminal
            android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, // android terminal
            iPhone: u.indexOf('iPhone') > -1, // Is it an iPhone or QQHD browser
            iPad: u.indexOf('iPad') > -1, // iPad
            webApp: u.indexOf('Safari') === -1, // Should the web program have no header and bottom
            weixin: u.indexOf('MicroMessenger') > -1, // Wechat
            qq: u.match(/\sQQ/i) === 'qq' // QQ
        }
    }()),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
}

8. Pop up window

1. Warning box: Window.alert ()

2. Input box: Window.prompt()

3. Confirmation box: Window.confirm()

DOM (document object model)

adopt HTML DOM,use JavaScript visit HTML All elements of the document.
When a web page is loaded, the browser creates a document object model of the page

DOM classification

Defines access and operations Front end training Standard method for HTML documents. DOM represents an HTML document as a tree structure

In html, everything is a node

  • Element node
  • Text node
  • Attribute node

The relationship of each node is parent-child relationship \ brother relationship

Through the programmable object model, JavaScript has gained enough power to create dynamic HTML

  • JavaScript can change all HTML elements in a page.
  • JavaScript can change all HTML attributes in a page.
  • JavaScript can change all CSS styles in a page.
  • JavaScript can respond to all events in the page.

DOM object

objectdescribe
Document: document objectEach HTML Document loaded into the browser becomes a Document object
Element: element objectAn Element object can have child nodes of type Element node, text node and comment node.
Attribute: node attribute objectAttr objects represent HTML attributes
Event: event objectThe element in which the event occurs, the state of the keyboard keys, the position of the mouse, and the shape of the mouse button

Document object

All properties of the Document object

attributedescribe
document.bodyGet body
document.HeadGet head
document.ElementGet html
document.cookieGet cookie
document.domainThe domain name of the current document can be used for cross domain operation
document.lastModifiedDate and time when the document was last modified
document.referrerurl of the current document
document.titletitle
document.URLThe URL of the current document

Document common methods

methoddescribe
document.write()Document write content
document.open()Open a stream to collect output from any document.write() or document.writeln() method.
document.close()Close the output stream opened with the document.open() method and display the selected data.
document.writeIn()Equivalent to the write() method, except that a newline character is written after each expression
Get element
document.getElementById()Get element by id
document.getElementsByName()Get the array of related elements through name
document.getElementsByTagName()A forEach loop cannot be used to get an array of related elements through a tag
document.getElementsByClassName()A forEach loop cannot be used to get an array of related elements through class
document.querySelector()Get the first tag object matching the criteria --- only one tag object will be obtained
document.querySelectorAll()Get the tag object of all matching conditions. The execution result is a pseudo array
Create element
document.createAttribute()Create attribute object
document.createElement()Create element object
document.createTextNode()Create text object
document.createComment()Create note

element document object

Common methods of element object

methoddescribe
Element addition, deletion, modification, cloning
appendChild(doc)Insert node to last
insertBefore(ndoc, oldoc)Before inserting a node into a node
removeChild(doc)Remove the node
replaceChild(doc)Replace node
cloneNode()Clone node
cloneNode(true)Clone nodes and their contents
Attribute correlation
getAttribute()get attribute
setAttribute()set a property
removeAttribute()Remove Attribute
getAttributeNode()Specify the attribute node
setAttributeNode()Set attribute node
removeAttributeNode()Remove attribute node
getElementsByTagName()Specifies the collection of all child elements of the tag name
nodelist.item()The node in the NodeList at the specified subscript
.classList.add()Add class
.classList.remove()Remove class

Common attributes of element object

attributedescribe
idElement id
stylestyle
classNameclass attribute
innerHMLLabel content
innerTextText content
Get node
childNodesGet element child nodes
parentNodeGet element parent node
attributesGet all properties
childrenGet all label child nodes
firstchildFirst child node
lastchildLast child node
firstElementchildFirst signature child node
lastElementChildLast signature child node
previousSiblingPrevious sibling node
nextsiblingNext sibling node
previousElementsiblingPrevious label
nextElemntSiblingNext label
parentNodeParent node
parentElementParent label node
nodeNameName: element node -- label name, attribute node -- attribute name, text node -- #text, comment node -- #comment
nodeTypeNode type: 1 element, 2 attribute, 3 text, 8 comment
nodeValueElement value: attribute value, text content and comment content
nodelist.lengthNumber of nodes in NodeList
Dimension distance
clientHeightHeight - content + padding
Clientwidthwidth
offsetHeightHeight - content + padding+border
Offsetwidthwidth
ClientTopTop border width
clientLeftMake border width
offsetTopParent top distance
offsetLeftLeft distance of parent object

DOM event operation

Mouse event

namedescribe
clickClick event
dbclickDouble click the event
contextmenuRight click event
mousedownPress the event to execute once
mouseupLift event
mousemoveMouse movement
mouseoverMove in
mouseoutremove
mouseenterMove in without bubbling
mouseleaveRemove without bubbling

Keyboard events

Get the event object when clicking

  • Normal version
    E/event
  • IE low version
    Window.event

Compatible writing method: VAR e = e|window.event

Obtain case related information

  • Key name:
    e.Key
  • Key code:
    e.Keycode
  • Compatible with Firefox:
    e.Which

Compatible writing method: e.keycode | e.Which

Alt key Ctrl key shift key determines whether to press alt ctrl shift

Touch Event

namedescribe
touchstartstart
touchendend
touchmovemove

Special events

namedescribe
animationendEnd of animation
transitionendExcessive end

Form Events

namedescribe
submitEvents triggered only when a form is submitted
focusEvent triggered when tag gets focus
inputEvents triggered when data is entered
changeLoss of addition and change of input data is the trigger event

Browser compatible processing

1. Browser scroll height

var height=document.documentElement.scrollTop||document.body.scrollTop
var width=document.documentElement.scrollLeft||document.body.scrollLeft
  • There is a document type declaration
document.documentElement.scrollTop
document.documentElement.scrollLeft
  • No document type declaration
document.body.scrollTop
document.body.scrollLeft

2. Get non inline style properties

The actual effect is to get the style properties of the label execution

if(window.getComputedStyle){
    window.getComponentStyle(dom).width
}else{
    doc.currentStyle.width
}

3. Get event object

dom.onclick=function(e){
    e=e||window.event
}

4. Get event object target

Compatible with low version Firefox browser, it is basically not used now

dom.event=function(){
    e=e||window.event
    var target=e.target||e.srcElement
}

5. Key value

Compatible with low version Firefox browser, it is basically not used now

document.onkeyup=function(e){
    e=e||window.event
   var keyNum=e.keyCode||e.which
}

6. Event listening / event registration

function myAddEvent(ele,type,fun){
    judge addEventListener Does this method exist
    if(ele.addEventListener){
        ele.addEventListener(type,fun)
    }else{
        ele.attachEvent('on'+type,fun)
    }
}

7. Delete event handler

function delFun(ele,type,fun){
    if(ele.removeEventListener){
        ele.removeEventListener(type,fun)
    }else{
        ele.detachEvent('on'+type,fun)
    }
}

8. Block event delivery

function stopBBle(e){
    if(e.stopPropagation){
        e.stopPropagation()
    }else{
        e.cancelBubble=true
    }
}

9. Block default event execution

if(e.preventDefault){
    e.preventDefault
}else{
    e.returnValue=false
}

10. ajax object

let xhr;
try{
    //Ordinary road blue flag
    xhr=new XMLHttpRequest()
}catch(e){
    //Compatible with IE lower version
    xhr=new ActiveXObject('Microsoft.XMLHTTP')
}
xhr.open('post','url')
xhr.setRequestHeader('content-type','application/x-www/form-url-encoded')
xhr.send('name=111&age=222')
//Standard browser
xhr.onload = function(){}
//Compatibility writing
xhr.onreadystatechange=function(){
    if(xhr.readystate==4){
        let reg=/^a\d{2}$/
        if(res.test(xhr.status)){
            console.lof(json.parse(xhr.response))
        }
    }
}

Compatibility writing method, encapsulation tool

Generate verification code function

function mySetVc() {
    var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXUZ';
    var newStr = '';
    for (var i = 1; i <= 6; i++) {
        var num = parseInt(Math.random() * str.length)

        if (newStr.indexOf(str[num]) === -1) {
            newStr += str[num];
        } else {
            i--;
        }
    }

    return newStr;
}

Get address bar data information

function getUrlVal() {
    // 1. Get the address bar parameter string
    let str = decodeURI(window.location.search).substr(1);

    // Create an object that stores the results
    let obj = {};

    // 2 into an array according to semicolon spaces
    const arr1 = str.split('&')

    // 3 circular variable array, which divides the data string into an array according to the = equal sign
    arr1.forEach(v => {
        let arr2 = v.split('=');
        obj[arr2[0]] = arr2[1];
    })

    return obj;

}

Generate table function

// Parameter 1: array, the data array to be referenced
// Parameter 2: label, the label object whose content needs to be written
function mySetTable(array, element) {
    var str = '';
    array.forEach(function (v, k) {
        str += '<tr>';
        for (var key in v) {
            str += `<td>${v[key]}</td>`;
        }
        str += `<td><button index="${k}">delete</button></td>`
        str += '</tr>';
    });
    element.innerHTML = str;
    var oBtns = document.querySelectorAll('button');

    mySetButton(oBtns, array, element);
}

Bind delete effect function to button

// Parameter 1,button button array
// Parameter 2, data array
// Parameter 3, label object for writing content
function mySetButton(BtnArray, array, element) {
    BtnArray.forEach(function (v) {
        v.onclick = function () {
            var bool = window.confirm('determine,Delete');
            if (bool) {
                var index = v.getAttribute('index');
                array.splice(index, 1);
                mySetTable(array, element);
            }
        }
    })
}

Handle listener event compatibility function

// Parameter 1: the tag object of the event needs to be bound
// Parameter 2: event type to be bound, no on
// Parameter 3: event handler to be bound
function myAddEvent(element, type, fun) {
    if (element.addEventListener) {
        // Normal browser
        element.addEventListener(type, fun);
    } else {
        // Low version IE browser
        element.attachEvent('on' + type, fun);
    }
}

Get css style function

// Parameter 1, label object requiring attribute
// Parameter 2, the attribute name of the attribute is required

function myGetStyle(element, type) {
    if (window.getComputedStyle) {
        return window.getComputedStyle(element)[type];
    } else {
        return element.currentStyle[type];
    }
}

Set cookie function

// Parameter 1: key name of cookie
// Parameter 2: key value of cookie
// Parameter 3: cookie aging (seconds)

function mySetCookie(key, value, time) {
    // 1. Get the current time object
    const nowTime = new Date();

    // 2. Obtain the timestamp of the current time -- the unit is milliseconds
    let timeStamp = nowTime.getTime();

    // 3. Calculate time stamp current time stamp - 8 hours + effective time (seconds)
    // Get the time stamp with time effect, which is the world standard time
    let newTimeStamp = timeStamp - 8 * 60 * 60 * 1000 + time * 1000;

    // 4. Set the timestamp back to the time object
    nowTime.setTime(newTimeStamp);

    // 5. Compatible with the case where the third parameter is not transmitted
    // If time is undefined, it is proved that there is no third parameter, execute session aging and assign an empty string
    // If the time is not undefined, it is proved that there is no third parameter, and the timestamp aging in the nowTime time time object is executed
    let endTime = time === undefined ? '' : nowTime;

    // 6. Set cookie s
    // Set an additional attribute to the cookie, path=/
    // Let all files in www use the set cookie
    document.cookie = `${key}=${value};expires=${endTime};path=/`;

}

Get the specific data of the cookie

function myGetCookie() {
    // Create an object that stores the results
    let obj = {};

    // 1 get cookie string
    let str = document.cookie;

    // 2 into an array according to semicolon spaces
    const arr1 = str.split('; ')

    // 3 circular variable array, which divides the data string into an array according to the = equal sign
    arr1.forEach(v => {
        let arr2 = v.split('=');
        obj[arr2[0]] = arr2[1];
    })

    return obj;
}

function fun(){
    console.log('I'm new js Content in file,Did you compress me?')
}

Topics: Front-end Database Redis Cache