Those holes in JavaScript that manipulate the DOM

Source: Internet
Author: User
Tags tagname

JS in the operation of the DOM there are many cross-browser aspects of the pit, this article took me nearly a week to tidy up, I will be based on the example to organize those big and small "pit."

The DOM works by loading the static content of the document and then dynamically refreshing it, and the dynamic refresh does not affect the static content of the document.

All DOM objects in Ps:ie are implemented in the form of COM objects, which means that the DOM in IE may differ somewhat from other browsers.

Node interface
Features/Methods type/return type Description
NodeName String The name of the node, as defined by the type of the node
NodeValue String The value of the node, as defined by the type of the node
NodeType Number One of the type constant values of the node
Ownerdocument Document Returns the root element of an element
FirstChild Node Point to the first node in the ChildNodes list
LastChild Node Point to the last node in the ChildNodes list
ChildNodes NodeList List of all child nodes
PreviousSibling Node Returns the previous sibling node of the selected node, or null if it does not exist
NextSibling Node Returns the next sibling node of the selected node, or null if it does not exist
HasChildNodes () Boolean Returns true if the current element node has child nodes, otherwise false
Attributes NamedNodeMap Returns the NamedNodeMap containing the selected node property
AppendChild (node) Node Add node to the end of ChildNodes
RemoveChild (node) Node Remove node from childnodes
ReplaceChild (NewNode, OldNode) Node Replace OldNode in childnodes with NewNode
InsertBefore Node Insert new child nodes before existing child nodes

FirstChild equivalent to childnodes[0];lastchild equivalent to childnodes[box.childnodes.length-1].

NodeType Type of return node
--元素结点返回1--属性结点返回2--文本结点返回3
InnerHTML and NodeValue

Difference between the two

box.childNodes[0].nodeValue = ‘<strong>abc</strong>‘;//结果为:<strong>abc</strong>abcbox.innerHTML = ‘<strong>abc</strong>‘;//结果为:abc

NodeName property gets the node name.

TagName
document.getElementByTagName(tagName):返回一个数组,包含对这些结点的引用

The getElementsByTagName () method returns an array of objects htmlcollection (NodeList), which holds a list of all nodes of the same element name.

document.getElementsByTagName(‘*‘);//获取所有元素

The Ps:ie browser uses wildcards as the first element node for the document's canonical declaration of the HTML that begins at the beginning.

document.getElementsByTagName(‘li‘);//获取所有 li 元素,返回数组document.getElementsByTagName(‘li‘)[0];//获取第一个 li 元素,HTMLLIElementdocument.getElementsByTagName(‘li‘).item(0);//获取第一个 li 元素,HTMLLIElementdocument.getElementsByTagName(‘li‘).length;//获取所有 li 元素的数目
Absolute references to nodes:
返回文档的根节点:document.documentElement返回当前文档中被击活的标签节点:document.activeElement返回鼠标移出的源节点:event.fromElement返回鼠标移入的源节点:event.toElement返回激活事件的源节点:event.srcElement
Relative references to nodes: (Sets the current node to nodes)
Node information
Create a new node
createDocumentFragment()--创建文档碎片节点createElement(tagname)--创建标签名为tagname的元素createTextNode(text)--创建包含文本text的文本节点
Get the location of a mouse click event
document.onclick = mouseClick;function mouseClick(ev){    ev = ev || window.event;//window.event用来兼容IE    var x = 0; var y = 0;    if(ev.pageX){        x = ev.pageX;        y = ev.pageY;    }else if(ev.clientX){        var offsetX = 0 , offsetY = 0;        if(document.documentElement.scrollLeft){            offsetX = document.documentElement.scrollLeft;            offsetY = document.documentElement.scrollTop;        }else if(document.body){            offsetX = document.body.scrollLeft;            offsetY = document.body.scrollTop;        }        x = ev.clientX + offsetX;        y = ev.clientY + offsetY;    }    alert("你点击的位置是 x="+ x + " y=" + y);}

The properties described below are supported by both Chrome and Safari.

Problem one: Firefox,chrome, Safari, and IE9 all use the Pagex and Pagey properties of non-standard events to get the mouse position of the Web page. Pagex/y gets the distance from the upper-left corner of the trigger point relative to the document area, with the page as the reference point, not as the slider moves.

Problem two: in IE, the event object has x, y attribute (the x-coordinate and y-coordinate where the event occurred) is not in Firefox. In Firefox, the equivalent of Event.x is Event.pagex. Event.clientx and Event.pagex have subtle differences (when the entire page has scroll bars), but most of the time they are equivalent.

Offsetx:ie is unique and chrome is supported. The mouse is compared to the position of the element that triggered the event, and the upper-left corner of the content area of the element box model is the reference point, and if there is a boder, a negative value may occur

Question three:
ScrollTop the distance that the scroll bar moves down, and all browsers support Document.documentelement.

Other references: 1190000002559158#articleheader11

Reference table

(+ for support,-for not supported):

offsetX/offsetY:W3C- IE+ Firefox- Opera+ Safari+ chrome+x/y:W3C- IE+ Firefox- Opera+ Safari+ chrome+layerX/layerY:W3C- IE- Firefox+ Opera- Safari+ chrome+pageX/pageY:W3C- IE- Firefox+ Opera+ Safari+ chrome+clientX/clientY:W3C+ IE+ Firefox+ Opera+ Safari+ chrome+screenX/screenY:W3C+ IE+ Firefox+ Opera+ Safari+ chrome+

View Demo below:
You will find that offsetx is undefined under Firefox and will appear normally in Chrome and IE.

https://jsfiddle.net/f4am208m/embedded/result/

Offsetleft and Style.left differences
1.style.left返回的是字符串,比如10px。而offsetLeft返回的是数值,比如数值102.style.left是可读写的,offsetLeft是只读的3.style.left的值需要事先定义(在样式表中定义无效,只能取到在html中定义的值),否则取到的值是空的
getComputedStyle and Currentstyle

getComputedStyle () accepts two parameters: to get the element of a calculated style and a pseudo-element, it can be null if no pseudo-element is required. However, in IE, Getcomputedstyle,ie is not supported to provide the Currentstyle property.

getComputedStyle (obj, false) is a support (FF12, Chrome 14, Safari): In the new version of FF only the first parameter is required, that is, the operand, the second parameter write "False" is also a common use of the wording, The goal is to be compatible with older versions of Firefox.
Cons: Normal in standard browser, but not supported in IE6/7/8

 window.onload=function(){    var oBtn=document.getElementById(‘btn‘);    var oDiv=document.getElementById(‘div1‘);    oBtn.onclick=function(){        //alert(oDiv.style.width); //写在样式表里无法读取,只能得到写在行内的        //alert(getComputedStyle(oDiv).width); //适用于标准浏览器       IE6、7、8不识别        //alert(oDiv.currentStyle.width); //适用于IE浏览器,标准浏览器不识别        if(oDiv.currentStyle){            alert(oDiv.currentStyle.width);        }else{            alert(getComputedStyle(oDiv).width);        }    };};
Cancel form Submission
<script type="text/javascript">    function listenEvent(eventObj,event,eventHandler){        if(eventObj.addEventListener){            eventObj.addEventListener(event,eventHandler,false);        }else if(eventObj.attachEvent){            event = "on" + event;            eventObj.attachEvent(event,eventHandler);        }else{            eventObj["on" + event] = eventHandler;        }    }    function cancelEvent(event){        if(event.preventDefault){            event.preventDefault();//w3c        }else{            event.returnValue = true;//IE        }    }    window.onload = function () {        var form = document.forms["picker"];        listenEvent(form,"submit",validateFields);    };    function validateFields(evt){        evt = evt ? evt : window.event;        ...        if(invalid){            cancelEvent(evt);        }    }</script>
Determine the size of the browser window

For mainstream browsers such as IE9, Firefox,chrome, and Safari, Window object properties called Innerwidth and Innerheight are supported, which returns the viewport area of the window minus the size of any scroll bars. IE does not support innerwidth and innerheight

<script type="text/javascript">    function size(){        var w = 0, h=0;        if(!window.innerWidth){            w = (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth);            h = (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight);        }else{            w = window.innerWidth;            h = window.innerHeight;        }        return {width:w,height:h};    }    console.log(size());//Object { width: 1366, height: 633 }</script>

Practical JavaScript scenarios (all browsers included):

var w=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;var h=window.innerHeight || document.documentElement.clientHeight|| document.body.clientHeight;

The scenarios for IE 6, 7, 8 are as follows:

document.documentElement.clientHeightdocument.documentElement.clientWidth

Or

document.body.clientHeightdocument.body.clientWidth

The Body property of the Document object corresponds to the <body> tag of the HTML documents. The DocumentElement property of the Document object represents the root node of the HTML documents.

Attributes property

The Attributes property returns a collection of attribute nodes for the node.

document.getElementById(‘box‘).attributes//NamedNodeMapdocument.getElementById(‘box‘).attributes.length;//返回属性节点个数document.getElementById(‘box‘).attributes[0]; //Attr,返回最后一个属性节点document.getElementById(‘box‘).attributes[0].nodeType; //2,节点类型document.getElementById(‘box‘).attributes[0].nodeValue; //属性值document.getElementById(‘box‘).attributes[‘id‘]; //Attr,返回属性为 id 的节点document.getElementById(‘box‘).attributes.getNamedItem(‘id‘); //Attr
SetAttribute and GetAttribute

In IE, do not know the class attribute, you need to change the ClassName property, also, in Firefox, also do not know the classname attribute, Firefox only know the class attribute, so the usual practice is as follows:

element.setAttribute(class, value);  //for firefoxelement.setAttribute(className, value);  //for IE

IE: You can get custom properties by using methods that get general properties, or you can use GetAttribute () to derive a custom attribute
Firefox: Only use GetAttribute () to get a custom attribute.

Workaround: Unify by getattribute () get a custom attribute

document.getElementById(‘box‘).getAttribute(‘id‘);//获取元素的 id 值document.getElementById(‘box‘).id;//获取元素的 id 值document.getElementById(‘box‘).getAttribute(‘mydiv‘);//获取元素的自定义属性值document.getElementById(‘box‘).mydiv//获取元素的自定义属性值, IE 不支持非document.getElementById(‘box‘).getAttribute(‘class‘);//获取元素的 class 值,IE 不支持document.getElementById(‘box‘).getAttribute(‘className‘);//非 IE 不支持

PS: In IE7 and earlier versions of IE, using the SetAttribute () method to set the class and style properties is ineffective, although IE8 resolves the bug, but is not recommended.

RemoveAttribute () method
removeAttribute()可以移除 HTML 属性。document.getElementById(‘box‘).removeAttribute(‘style‘);//移除属性

Ps:ie6 and earlier versions do not support the RemoveAttribute () method.

Cross-browser Events event object
<!doctype html>
DataTransfer Object
Properties Description
DropEffect Sets or gets the type of drag operation and the type of cursor to display
Effectallowed Sets or gets the source element that the data transfer operation can apply to the object
Method Description
ClearData Remove one or more data formats from the Clipboard by DataTransfer or Clipboarddata objects
GetData Get data in the specified format from the Clipboard by DataTransfer or Clipboarddata objects
SetData Assigns data to a datatransfer or Clipboarddata object in the specified format
HTML5 drag-and-drop browser support

Internet Explorer 9, Firefox, Opera 12, Chrome, and Safari 5 support drag and drop

To make an element draggable, set the Draggable property to True:

Events Description
DragStart Drag and Drop event start
Drag On the drag operation
DragEnter Drag onto the target to determine whether the target accepts placement
DragOver Drag to the target to determine feedback to the user
Drop Placement occurs
DragLeave Drag to leave the target
Dragend End of drag operation

Some browser compatibility for the above code:

1.为了兼容IE,我们将`window.event`赋给 `evt`,其他浏览器则会正确将接收到的`event`对象赋给`evt`。2.w3c使用addEventListener来为事件元素添加事件监听器,而IE则使用attachEvent。addEventListener为事件冒泡到的当前对象,而attachEvent是window3.对于事件类型,IE需要加`on + type`属性,而其他浏览器则不用4.对于阻止元素的默认事件行为,下面是w3c和IE的做法:    e.preventDefault();//w3c       e.returnValue = false;//IE    5.对于取消事件传播,w3c和IE也有不同的处理机制:    e.stopPropagation();//w3c    e.cancelBubble = true;//IE
Get target objects across browsers
//跨浏览器获取目标对象function getTarget(ev){    if(ev.target){//w3c        return ev.target;    }else if(window.event.srcElement){//IE        return window.event.srcElement;    }}  

For the object that gets the trigger event, the Internet and IE also have different practices:

event.target;//w3cevent.srcElement;//IE  

We can use the three-mesh operator to be compatible with them:

obj = event.srcElement ? event.srcElement : event.target;
InnerText's Problem

InnerText in IE can work normally, but innertext in Firefox but not.

<p id="element"></p><script type="text/javascript">    if(navigator.appName.indexOf("Explorer") >-1){        document.getElementById(‘element‘).innerText = "my text";    } else{        document.getElementById(‘element‘).textContent = "my text";    }</script>
Get and set innertext across browsers
//跨浏览器获取innerTextfunction getInnerText(element){    return (typeof element.textContent == ‘string‘) ? element.textContent : element.innerText;} //跨浏览器设置innerTextfunction setInnerText(element,text){    if(typeof element.textContent == ‘string‘){        element.textContent = text;    }else{        element.innerText = text;    }}    
The use of Oninput,onpropertychange,onchange

The OnChange trigger event must meet two conditions:

a)当前对象属性改变,并且是由键盘或鼠标事件激发的(脚本触发无效)b)当前对象失去焦点(onblur);

Onpropertychange, as long as the current object property changes, will trigger the event, but it is exclusive to IE;

oninput是onpropertychange的非IE浏览器版本,支持firefox和opera等浏览器,但有一点不同,它绑定于对象时,并非该对象所有属性改变都能触发事件,它只在对象value值发生改变时奏效。
accessing XMLHttpRequest objects
<script type="text/javascript">    if(window.XMLHttpRequest){        xhr = new XMLHttpRequest();//非IE    }else if(window.ActiveXObject){        xhr = new ActiveXObject("Microsoft.XMLHttp");//IE    }</script>
Prevent page content from being selected
问题:  FF需要用CSS禁止,IE用JS禁止  解决方法:  IE: obj.onselectstart = function() {return false;}  FF: -moz-user-select:none;   
Three big non-bubbling events

All browser Focus/blur events are not bubbling, fortunately, most browsers support focusin/focusout events, but the nasty Firefox doesn't even support this.

IE6、7、8下 submit事件不冒泡。IE6、7、8下 change事件要等到blur时才触发。
The Evil Wheel Event

Roller event support is a mess, the following rules:

IE6-11 chrome mousewheel wheelDetla 下 -120 上 120firefox DOMMouseScroll detail 下3 上-3firefox wheel detlaY 下3 上-3IE9-11 wheel deltaY 下40 上-40chrome wheel deltaY 下100 上-100  

About mouse wheel events, ie support MouseWheel, Firefox support Dommousescroll.
To determine whether the mouse wheel is up or down, ie is through the Wheeldelta property, while Firefox is through the detail property

Event Delegate Method
//事件委托方法  IE:document.body.onload = inject; //Function inject()在这之前已被实现  FF:document.body.onload = inject();   
HTML5 Browser Support situation



Source Address: http://fmbip.com/litmus/

Query operations

A query refers to a set of elements that are found through some characteristic strings, or whether an element satisfies a string.

1. IE6/7不区分id和nam在IE6/7下使用getElementById和getElementsByName时会同时返回id或name与给定值相同的元素。由于name通常由后端约定,因此我们在写JS时,应保证id不与name重复。2. IE6/7不支持getElementsByClassName和querySelectorAll   这两个函数从IE8开始支持的,因此在IE6/7下,我们实际可以用的只有getElementByTagName。3. IE6/7不支持getElementsByTagName(‘*‘)会返回非元素节点    要么不用*,要么自己写个函数过滤一下。4. IE8下querySelectorAll对属性选择器不友好    几乎所有浏览器预定义的属性都有了问题,尽量使用自定义属性或者不用属性选择器。5. IE8下querySelectorAll不支持伪类    有时候伪类是很好用,IE8并不支持,jquery提供的:first、:last、:even、:odd、:eq、:nth、:lt、:gt并不是伪类,我们在任何时间都不要使用它们。6. IE9的matches函数不能处理不在DOM树上的元素只要元素不在dom树上,一定会返回false,实在不行把元素丢在body里面匹配完了再删掉吧,当然了我们也可以自己写匹配函数以避免回流。

Data reference:
http://w3help.org/zh-cn/kb/

1190000002650240#articleheader30

Http://www.jqhtml.com

Those holes in JavaScript that manipulate the DOM

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.