Js use in the process, often found on the IE browser compatibility issues, of course, Microsoft now he is going to abandon IE, launched edge browser, for front-end is good news.
However, the proportion of IE users still can not be underestimated, so the next organized here several common compatibility issues attach solutions, in order to avoid contingencies.
1. The acquisition of non-line style
IE browser: element.currentstyle + attr
Normal browser (chrome, FF): getComputedStyle (element, false) + attr
These two types are referred to as the following browsers IE and normal
The next package a function to facilitate the call (compatible with all browsers)
function getStyle(ele,attr){ var a = ""; if(ele.currentStyle){ //IE a = ele.currentStyle[attr]; }else{ a = getComputedStyle(ele,false)[attr]; //正常 }
2. Get event object
IE : window.event
Normal: to mass participation event
obox.onclick=function(eve){ var e=eve||window.event; console.log(e) }
3. stop event bubbling
function stopBubble(e){ if(e.stopPropagation){ e.stopPropagation(); //正常 }else{ e.cancelBubble = true; //IE } }
4. The event delegation
Event delegates: the same event multiple identical elements, added to the existing common parent element on the page, use event bubbling, with the event source, find the elements really clicked
function tar(t){ var t = e.target || e.srcElement;}
5. Add the event binding way
Event binding in two ways: listening assignment type and style
function addEvent (ELE, type, CB) { IF (ele.addEventListener) { ele.addEventListener (type, CB) // listener formula: Normal } the else IF (ele.attachEvent) { ele.attachEvent ( "ON" + type, CB) // listener formula: IEs } the else { ELE [ "ON" + type] = CB; // assignment of formula } }
6. Remove the event binding way
Also, delete the corresponding event binding way
function removeEvent (ELE, of the type, cb) { IF (ele.removeEventListener) { ele.removeEventListener (of the type, cb) // listens type: Normal delete } the else IF (ele.detachEvent) { ele.detachEvent ( "ON" + type, CB) // listener formula: IE deletion } the else { ELE [ "ON" + type] = null ; // delete the assignment type } }
7. acquire key keyboard events
IE : event.which
Normal: event.keycode
function code (Eve) { var E = || the window.event Eve; // first acquisition event var code = e.keyCode || e.which; // key reacquisition }
8. prevent the default event
function stopDefault(e){ if(e.preventDefault){ e.preventDefault() //正常 }else{ e.returnValue = false; //IE } }
The new encounter compatibility problems will continue to update, welcome to the discussion