js common compatibility summary 12

Summary of common JS compatibility issues

1> Scroll bar:

document.documentElement.scrollTop || document.body.scrollTop

2> Get style compatibility

function getStyle(dom, styleName){
	return dom.currentStyle? dom.currentStyle[styleName] : getComputedStyle(dom)[styleName];
}

3> Compatible with the visible area of ​​the webpage

window.innerHeight || document.documentElement.clientHeight
window.innerWidth || document.documentElement.clientWidth

4) Event object compatibility

evt = evt || window.event;

5) Prevent event bubbling compatible

event.stopPropagation ? event.stopPropagation() : event.cancelBubble=true; 

6) Prevent compatibility with default behaviors

evt.preventDefault?evt.preventDefault():evt.returnValue=false;

7) Event monitoring compatibility

if(document.all){
    dom.attactEvent(“onclick”, fn);
} else {
    dom.addEventListener(“click”, fn);
}

The following are some common examples of IE and Firefox compatibility of Javascript

1.document.formName.item(“itemName”) 问题

说明:IE下,可以使用document.formName.item("itemName")或document.formName.elements["elementName"];
Firefox下,只能使用document.formName.elements["elementName"].
解决方法:统一使用document.formName.elements["elementName"].

2. Collection object problem

Note: In IE, you can use () or [] to get collection objects; in Firefox, you can only use [] to get collection objects.
Solution: Use [] to get collection objects in a unified way.

3. Custom attribute issues

Note: Under IE, you can use the method of obtaining general attributes to obtain custom attributes, or you can use getAttribute() to obtain custom attributes; under Firefox, you can only use getAttribute() to obtain custom attributes.
Solution: Unified pass getAttribute( ) To get custom attributes.

4.eval("idName") problem

Note: In IE, you can use eval ( "idName") or getElementById ( "idName") to get the id idName of HTML objects; only use getElementById ( "idName") to get the id under Firefox is idName of HTML objects.
Solve Method: uniformly use getElementById("idName") to obtain the HTML object whose id is idName.

5. The problem that the variable name is the same as the ID of a certain HTML object

Note: Under IE, the ID of the HTML object can be used directly as the variable name of the document's subordinate object; under Firefox, it can't. Under Firefox, the same variable name as the HTML object ID can be used; under IE, it can't.
Solution: Use document.getElementById("idName") instead of document.idName. It is best not to take variable names with the same HTML object ID to reduce errors; when declaring variables, always add var to avoid ambiguity.

6.const problem

Note: In Firefox, you can use the const keyword or the var keyword to define constants; in IE, you can only use the var keyword to define constants.
Solution: Use the var keyword to define constants uniformly.

7.input.type attribute problem

Note: The input.type attribute under IE is read-only; but the input.type attribute under Firefox is read-write.

8.window.event problem

Note: window.event can only be run under IE, but not under Firefox. This is because Firefox's event can only be used at the scene of the event. Firefox must add event from the source for parameter transfer. Ie ignores this parameter and uses window.event to read the event.
Solution:

IE&Firefox:
Submitted(event)"/> …

function Submitted(evt) {
evt=evt?evt:(window.event?window.event:null);
}

9.event.x and event.y problems

Explanation: Under IE, the even object has x, y attributes, but does not have pageX, pageY attributes; under Firefox, the even object has pageX, pageY attributes, but does not have x, y attributes.
Solution: Use mX(mX = event.x? event.x: event.pageX;) instead of event.x under IE or event.pageX under Firefox.

10.event.srcElement problem

Explanation: Under IE, the event object has the srcElement attribute but no target attribute; under Firefox, the even object has the target attribute but no srcElement attribute.
Solution: Use obj(obj = event.srcElement? Event.srcElement: event.target; ) Instead of event.srcElement under IE or event.target under Firefox. Please also pay attention to the compatibility of events.

11.window.location.href problem

Note: In IE or Firefox 2.0.x, you can use window.location or window.location.href; in Firefox 1.5.x, you can only use window.location.
Solution: Use window.location instead of window.location. href.

12. Modal and non-modal window issues

Note: In IE, you can open modal and non-modal windows through showModalDialog and showModelessDialog; not in Firefox.
Solution: directly use window.open(pageURL,name,parameters) to open a new window.
If you need to pass the parameters in the child window back to the parent window, you can use window.opener in the child window to access the parent window.
For example: var parWin = window.opener; parWin.document.getElementById("Aqing").value = " Aqing";

13.frame problem

Take the following frame as an example:

<frame src="xxx.html" id="frameId" name="frameName" />

(1) Access the frame object:

IE: Use window.frameId or window.frameName to access this frame object. FrameId and frameName can have the same name.
Firefox: You can only use window.frameName to access this frame object.
In addition, you can use window.document.getElementById("frameId") to access this frame object in both IE and Firefox.

(2) Switch frame content:

In IE and Firefox, you can use window.document.getElementById("testFrame").src = "xxx.html" or window.frameName.location = "xxx.html" to switch the content of the frame.
If you need to change the content of the frame The parameter is passed back to the parent window (note that it is not an opener, but a parent frame), and you can use parent in frme to access the parent window.
For example: parent.document.form1.filename.value="Aqing";

14.body problem

The body of Firefox exists before the body tag is completely read by the browser; the body of IE must exist after the body tag is completely read by the browser.

15. Event delegation method

IE:document.body.onload = inject; //Function inject()在这之前已被实现
Firefox:document.body.onload = inject();

16. The difference between firefox and IE's parent element (parentElement)

IE: obj.parentElement
firefox: obj.parentNode
Solution: Because both firefox and IE support DOM, using obj.parentNode is a good choice.

17.cursor:handVS cursor:pointer

Firefox does not support hand, but ie supports pointer.
Solution: Use pointer uniformly

18. innerText works normally in IE, but innerText does not work in FireFox. TextContent is required.

Solution:

if(navigator.appName.indexOf("Explorer") > -1){
	document.getElementById('element').innerText = "my text";
} else {
	document.getElementById('element').textContent = "my text";
}

19. When setting the style of HTML tags in FireFox, all positional and font size values ​​must be followed by px. This ie is also supported.

20. IE, Firefox and other browsers have different operations on table tags. In IE, it is not allowed to assign values ​​to the innerHTML of table and tr. When using js to add a tr, the appendChild method does not work.

Solution:

//向table追加一个空行:

var row = otable.insertRow(-1);
var cell = document.createElement("td");
cell.innerHTML = " ";
cell.className = "XXXX";
row.appendChild(cell);

21.Padding problem

padding 5px 4px 3px 1px; FireFox无法解释简写,
必须改成 padding-top:5px; padding-right:4px; padding-bottom:3px; padding-left:1px;

22. When eliminating the indentation of lists such as ul, ol, etc.

样式应写成:list-style:none;margin:0px;padding:0px;
其中margin属性对IE有效,padding属性对FireFox有效

23. CSS transparency

IE:filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=60).
FF:opacity:0.6。

24.CSS rounded corners

IE:不支持圆角。
FF:-moz-border-radius:4px,或者-moz-border-radius-topleft:4px;-moz-border- radius-topright:4px;-moz-border-radius-bottomleft:4px;-moz-border- radius- bottomright:4px;.

25.CSS double-line bump border

IE: border:2px outset;。
FF: -moz-border-top-colors: #d4d0c8 white;-moz-border-left-colors: #d4d0c8 white;-moz-border-right-colors:#404040 #808080;-moz-border-bottom-colors:#404040 #808080;

26. Operate the select options collection

枚举元素除了[]外,SelectName.options.item()也是可以的, 另外SelectName.options.length, SelectName.options.add/remove都可以在两种浏览器上使用。注意在add后赋值元素,否则会失败(本人试验如此)。

27. The difference between XMLHTTP

//FF
if (window.XMLHttpRequest) {
	xmlhttp = new XMLHttpRequest()
	xmlhttp.onreadystatechange=xmlhttpChange
	xmlhttp.open("GET",url,true)
	xmlhttp.send(null)
}
//IE
else if (window.ActiveXObject) {
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
	if (xmlhttp) {
	xmlhttp.onreadystatechange=xmlhttpChange
	xmlhttp.open("GET",url,true)
	xmlhttp.send()
	}
}

28.innerHTML的区别
Firefox不支持innerHTML, 解决办法可以如下
rng = document.createRange();
el = document.getElementById(elementid);
rng.setStartBefore(el);
htmlFrag = rng.createContextualFragment(content);
while (el.hasChildNodes()) //清除原有内容,加入新内容
el.removeChild(el.lastChild);
el.appendChild(htmlFrag);

分类: javascript
关于用“索引”获取字符串每一项出现的兼容性问题:
对于字符串也有类似于数组 这样的通过 下标索引 获取每一项的值,
var str=“abcde”;
alert(str[1]);
但是低版本的浏览器IE6,7不兼容
解决方法:

str.charAt(i)    //全部浏览器都兼容
var str="abcde";
for(var i=0;i<str.length;i++){
  alert(str.charAt(i));   //放回字符串中的每一项
}

关于获取行外样式 currentStyle 和 getComputedStyle 出现的兼容性问题
我们都知道js通过style不可以获取行外样式,当我们需要获取行外样式时:
我们一般通过这两个方法获取行外样式:
IE下: currentStyle
Chrome,FF下: getComputedStyle(oDiv,false)
兼容两个浏览器的写法:

  if(oDiv.currentStyle){
      alert(oDiv.currentStyle.width);
  } else {
      alert(getComputedStyle(oDiv,false).width);
  }

*注:在解决很多兼容性写法时,都是用if…else…

封装一个获取行外样式的函数:(兼容所有浏览器,包括低版本IE6,7)

   funtion getStyle(obj,name){
       if (obj.currentStyle) {
           //IE
           return obj.currentStyle[name];
       } else {
           //Chrom,FF
           return getComputedStyle(obj,false)[name];
       }
   }
   getStyle(oDiv,'width');

关于DOM中 childNodes 获取子节点出现的兼容性问题
childNodes:获取子节点,
–IE6-8:获取的是元素节点,正常
–高版本浏览器:但是会包含文本节点和元素节点(不正常)
解决方法: 使用nodeType:节点的类型,并作出判断
–nodeType=3–>文本节点
–nodeTyPE=1–>元素节点
例: 获取ul里所有的子节点,让所有的子节点背景色变成红色
获取元素子节点兼容的方法:
var oUl=document.getElementById('ul');
for(var i=0;i<oUl.childNodes.length;i++){
  if(oUl.childNodes[i].nodeType==1){
    oUl.childNodes[i].style.background='red';
  }
}

备注:上面childNodes为我们带来的困扰完全可以有children属性来代替。
children属性:只获取元素节点,不获取文本节点,兼容所有的浏览器,
比上面的好用所以我们一般获取子节点时,最好用children属性。
var oUl=document.getElementById('ul');
oUl.children.style.background="red";

关于使用 firstChild,lastChild 等,获取第一个/最后一个元素节点时产生的问题
–IE6-8下: firstChild,lastChild,nextSibling,previousSibling,获取第一个元素节点
(高版本浏览器IE9+,FF,Chrome不兼容,其获取的空白文本节点)
–高版本浏览器下: firstElementChild,lastElementChild,nextElementSibling,previousElementSibling
(低版本浏览器IE6-8不兼容)
–兼容写法: 找到ul的第一个元素节点,并将其背景色变成红色

var oUl=document.getElementById('ul');
if(oUl.firstElementChild){
  //高版本浏览器
  oUl.firstElementChild.style.background='red';
}else{
  //IE6-8
  oUl.firstChild.style.background='red';
}

Regarding the use of the event object, compatibility issues
such as: obtaining the mouse position

IE/Chrom: event.clientX;event.clientY
FF/IE9以上/Chrom: 传参ev–> ev.clientX;ev.clientY
获取event对象兼容性写法:

var oEvent==ev||event;
   document.oncilck=function(ev){
       var oEvent==ev||event;
       if(oEvent){
           alert(oEvent.clientX);
       }
   }

Regarding binding two identical events to an element: attachEvent/attachEventLister compatibility issues.
Event binding: (incompatibility requires two combinations for compatibility if...else...)

IE8 and below use: attachEvent('event name',fn);
For FF, Chrome, IE9-10: attachEventLister('event name', fn, false);
multiple event bindings are encapsulated into a compatible function:

function myAddEvent(obj,ev,fn){
  if(obj.attachEvent){
    //IE8以下
    obj.attachEvent('on'+ev,fn);
  }else{
    //FF,Chrome,IE9-10
    obj.attachEventLister(ev,fn,false);
  }
}
myAddEvent(oBtn,'click',function(){
  alert(a);
});
myAddEvent(oBtn,'click',function(){
  alert(b);
});

Questions about getting the scroll bar distanceWhen
we get the scroll bar distance:

IE,Chrome: document.body.scrollTop
FF: document.documentElement.scrollTop
解决方法:

var scrollTop=document.documentElement.scrollTop||document.body.scrollTop

Guess you like

Origin blog.csdn.net/qq_45555960/article/details/102868564