[with] cross browser development work summary

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

from:

Great summary, had to turn

This summary is in 2011 summary, Make a product cross browser compatible work at that time, Because the product development time is early, In the beginning only in the following IE (IE 8, IE 9 and a little bit of use), When doing cross browser compatible work, Mainly is the adaptation of IE 6--IE 9, Safari, FireFox, Chrome, Transformation introduced jQuery framework, Most of the functions can be used normally, We will summarize the share.

1.eval(idName)

[Problem description]: IE, safari, ChromeThe browser can be usedeval(idName)OrgetElementById(idName)To obtainidFor theidNameTheHTMLObject, firefoxOnly usegetElementById(idName)To obtainidFor theidNameTheHTMLObject.

[Methods: use getElementById compatible] (" idName" ID) to obtain the idName HTML object.

2.ActiveXObject 

[Problem description]: IE support the use of VaR obj = new (ActiveXObject) way of creating objects, but other browsers will prompt the ActiveXObject object is not defined.

[Compatible way]:

(1)In the use of new (ActiveXObject) before judging whether the browser supports ActiveXObject objects, to create the AJAX object as an example:

Copy code
1 if(window.ActiveXObject)

2 {
3 this.req=new ActiveXObject("Microsoft.XMLHTTP");
4 }
5 else if(window.XMLHttpRequest)
6 {
7 this.req=new XMLHttpRequest();
8 }

<div class="cnblogs_code_toolbar"><span class="cnblogs_code_copy"><a title="Copy the code " onclick=" copyCnblogsCode (this) " href=" javascript:void (0); " > <img alt=" copy code" src=" ; /></a></span></div>

(2)The Ajax method uses the jQuery package to create objects, to create the AJAX object as an exampleRecommend.:

Copy code
 1 var strResponse = "";
 2 jQuery.ajax({ url: sAspFile, data: "<root>" + sSend + "</root>", processData: false, async: false, type: "POST",
 3     error: function(XMLHttpRequest, textStatus, errorThrown) 
 4     {
 5             strResponse = textStatus;
 6     },
 7      success: function(data, textStatus)
 8      {
 9             strResponse = data;
10     } 
11 });
Copy code

 3.XMLOperation

[Problem Description:] usually loading xml document using the ActiveXObject object, but until the IE, other browsers do not support this method. The operation of XML document, IE and other browsers have different methods of XML text, generally in the XML object is xml.documentElement.xml, but the XML attribute is only supported on IE, other browsers do not support. Find node is commonly used methods of selectNodes and selectSingleNode, these two methods are supported only in IE, other browsers need to expand.

[Compatible way]

(1)Load the XML document: $.ajax (), refer to the jQuery help documentation

(2)The XML object to a string, such as:

Copy code
 1 var stringtoxml = function(str) { //String to the XML object
 2     var s = "<?xml version='1.0' encoding='utf-8' ?>" + str;
 3     var objxml = null;
 4     if (window.ActiveXObject) {
 5         objxml = new ActiveXObject("Microsoft.XMLDOM");
 6         objxml.async = false;
 7         objxml.loadXML(s);
 8     }
 9     else {
10         objxml = (new DOMParser()).parseFromString(s, "text/xml");
11     }
12     return objxml;
13 }
14 
15 var xmltostring = function(dom) {  //The XML object to a string
16     if (dom instanceof jQuery) {
17         dom = dom[0];
18     }
19     var str = null;
20     if (window.ActiveXObject) {
21         str = dom.xml;
22     }
23     else {
24         str = (new XMLSerializer()).serializeToString(dom);
25     }
26     return str;
27 }
28 
29 var oXMLO = stringtoxml("<root>"+ xml +"</root>");
30 var root = oXMLO.documentElement;
31 var strXml = xmltostring(root).replace("<root>","");
Copy code

(3)String XML objects, such as:

1 var oXML = stringtoxml("<root>" + document.getElementById("hidTaskXml").value + "</root>");

(4)Search node: can use the find method JQUERY to search node, such as:

1 var item = $(oXML).find("record");

Or use a prototype extension method add selectNodes and selectSingleNode methods for the XML object, extension methods are as follows:

Copy code
if( document.implementation.hasFeature("XPath", "3.0") ) 
{
    XMLDocument.prototype.selectNodes =function(cXPathString, xNode) 
    {
        if( !xNode ) 
        { 
            xNode = this; 
        } 
        var oNSResolver = this.createNSResolver(this.documentElement); 

        var aItems = this.evaluate(cXPathString, xNode, oNSResolver,

        XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null) ;

        var aResult = []; 

        for( var i = 0; i <aItems.snapshotLength; i++)
        {     
            aResult[i] = aItems.snapshotItem(i); 
        } 

        return aResult; 
     } 

    Element.prototype.selectNodes = function(cXPathString)
     {     
        if(this.ownerDocument.selectNodes)
        {          
            return this.ownerDocument.selectNodes(cXPathString, this);     
        } 
        else
        {     
            throw "For XML Elements Only";    
        }  
     }

    XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode) 
    {
        if( !xNode ) 
        {  
           xNode = this; 
        } 
        var xItems = this.selectNodes(cXPathString, xNode);   
        if( xItems.length > 0 )
        {     
             return xItems[0];   
        } 
        else 
        {   
            return null;   
        } 
    } 

    Element.prototype.selectSingleNode = function(cXPathString) 
    {    
        if(this.ownerDocument.selectSingleNode) 
        {       
            return this.ownerDocument.selectSingleNode(cXPathString, this);   
        } 
        else
        {      
            throw "For XML Elements Only";
        }    
     }  
}            
Copy code

4.window.execScript() 

[Problem description]: only IE browser supports the execScript method, the other is not supported. But all browsers support window.eval () method.

[Methods: using window.eval compatible] () instead of window.execScript (). Such as

1 //window.execScript("alert(123)");
2 
3 window.eval("alert(123)");

5.window.createPopup()

[Problem description]: method to create a pop-up window, IE support this method, Safari, FireFox, Chrome does not support, use will suggest that createPopup method is not defined.

[Compatible way]: the following methods can be used to add the createPopup method for window object.

Copy code
if (!window.createPopup) {   
    var __createPopup = function() {   
        var SetElementStyles = function( element, styleDict ) {   
            var style = element.style ;   
            for ( var styleName in styleDict )style[ styleName ] = styleDict[ styleName ] ;    
        }   
        var eDiv = document.createElement( 'div' );    
        SetElementStyles( eDiv, { 'position': 'absolute', 'top': 0 + 'px', 'left': 0 + 'px', 'width': 0 + 'px', 'height': 0 + 'px', 'zIndex': 1000, 'display' : 'none', 'overflow' : 'hidden' } ) ;   
        eDiv.body = eDiv ;   
        var opened = false ;   
        var setOpened = function( b ) {   
            opened = b;    
        }   

        var getOpened = function() {   
            return opened ;    
        }   

        var getCoordinates = function( oElement ) {   
            var coordinates = {x:0,y:0} ;    
            while( oElement ) {   
                coordinates.x += oElement.offsetLeft ;   
                coordinates.y += oElement.offsetTop ;   
                oElement = oElement.offsetParent ;   
            }   
            return coordinates ;   
        }   
        return {
            htmlTxt : '', 
      document : eDiv, 
      isOpen : getOpened(), 
      isShow : false, 
      hide : function() { 
       SetElementStyles( eDiv, { 'top': 0 + 'px', 'left': 0 + 'px', 'width': 0 + 'px', 'height': 0 + 'px', 'display' : 'none' } ) ; 
       eDiv.innerHTML = '' ; 
       this.isShow = false ; 
      }, 
      show : function( iX, iY, iWidth, iHeight, oElement ) { 
       if (!getOpened()) { 
        document.body.appendChild( eDiv ) ; setOpened( true ) ; 
       } ; 
       this.htmlTxt = eDiv.innerHTML ; 
       if (this.isShow) { 
           this.hide() ; 
       } ; 
       eDiv.innerHTML = this.htmlTxt ; 
       var coordinates = getCoordinates ( oElement ) ; 
       eDiv.style.top = ( iX + coordinates.x ) + 'px' ; 
       eDiv.style.left = ( iY + coordinates.y ) + 'px' ; 
       eDiv.style.width = iWidth + 'px' ; 
       eDiv.style.height = iHeight + 'px' ; 
       eDiv.style.display = 'block' ; 
       this.isShow = true ; 
      } 
  }   
    }   
    window.createPopup = function() {   
        return __createPopup();    
    }   
}
Copy code

6.getYear()Method

[Description of the problem: the following code]:

1 var year= new Date().getYear();
2 
3 document.write(year);

Get in the IE date is " 2011", seen in Firefox date is " 111", mainly because the return getYear in Firefox is " the -1900" value of the current year.

[Compatible way]: the solution is coupled with years of judgement, such as:

1 var year= new Date().getYear();
2 year = (year<1900?(1900+year):year);
3 document.write(year);

Can also use a getFullYear getUTCFullYear to call:

1 var year = new Date().getFullYear();
2 
3 document.write(year);

7.document.all 

[Problem description]: document.all can be used in IE, Safari, not Firefox, Chrome use

[Methods: all compatible] to the document.all.* method to obtain the object are changed to document.getElementById or document.getElementsByName or document.getElementsByTagName.

The 8 variable name and object ID the same problem

[Problem Description: IE], HTML ID can be used directly as document subordinate object variable names, such as the following notation:

objid.value = "123";//Objid control ID

Other browsers do not write this. The reason is the other browsers, can be used with the HTML object ID of the same name, IE is not.

[Compatible way]: the use of document.getElementById (idName) and other general method to obtain the object, and then conduct other operations. Such as:

document.getElementById(objid).value = "123"; //Objid control ID

Note: it is best not to take the HTML object ID of the same name, in order to reduce the error; in when you declare a variable, all with VaR, in order to avoid ambiguity.

The add method of 9.select element

[Problem Description:] in IE, Safari, Chrome, select control when adding an item using the following:

document.getElementById("select1").add(new Options("aa","aa"));

But in FireFox this operation will be in error.

[Methods: using a compatible compatible] unified method, add options attribute, as follows:

document.getElementById("select1").options.add(new Options("aa","aa"));

The custom attributes of the 10.html elements

[Problem description]: such as the document.getElementById method element attribute access in IE (ID). The attribute name, but also for the custom attributes and non custom attributes are valid. Public property but in other browsers and the method is only applied to elements, the custom attribute is not take.

[Compatible way]: use the jQuery method to take, such as $("#id").Attr ("property") or document.getElementById (ID).GetAttribute ("property"), the two methods can be applied to all browser.

11.html elements innerText attribute

[Problem Description:] attribute innerText element text can work properly in IE, but this property is not the standard of DHTML, other browsers do not support, other browsers use the textContent property to get the.

[Compatible way]:

(1)The general method is to use the jQuery method $("#id").Text (), such as:

//document.getElementById(id).innerText;

$("#id").text();

(2)The value judgment of the browser before, according to the specific situation of values, such as:

var obj = document.getElementById(id);

var str = (obj.innerText)?obj.innerText:obj.textContent;

(3)You can also add innerText elements through prototype expansion method, extension methods are as follows:

Copy code
if(typeof(HTMLElement)!="undefined" && !window.opera) 
{ 
    var pro = window.HTMLElement.prototype;     

    pro.__defineGetter__("innerText",function (){ 
        var anyString = ""; 
        var childS = this.childNodes; 
        for(var i=0; i<childS.length; i++) 
        { 
            if(childS[i].nodeType==1)
            { 
                anyString += childS[i].tagName=="BR" ? '\n' : childS[i].innerText; 
            }
            else if(childS[i].nodeType==3) 
            {
                anyString += childS[i].nodeValue; 
            }
        } 
        return anyString; 
     }); 

     pro.__defineSetter__("innerText",function(sText){
        this.textContent=sText; 
     });   
}
Copy code

12.html elements innerHTML, outerHTML attribute 

[Problem Description: innerHTML] is the attribute all browsers support. The outerHTML property is not the standard of DHTML, IE and other browsers do not support.

[Compatible way]: in non IE browser must use the expansion method to obtain, extension methods are as follows:

Copy code
if(typeof(HTMLElement)!="undefined" && !window.opera) 
{ 
     var pro = window.HTMLElement.prototype;     
     pro.__defineGetter__("outerHTML", function(){     
          var str = "<" + this.tagName;     
          var a = this.attributes;     
          for(var i = 0, len = a.length; i <len; i++)
          {     
               if(a[i].specified)
               {     
                    str += " " + a[i].name + '="' + a[i].value + '"';     
               }     
          }     
          if(!this.canHaveChildren)
          {     
               return str + " />";     
          }     
          return str + ">" + this.innerHTML + "</" + this.tagName + ">";     
     });     

      pro.__defineSetter__("outerHTML", function(s){     
          var r = this.ownerDocument.createRange();     
          r.setStartBefore(this);     
          var df = r.createContextualFragment(s);     
          this.parentNode.replaceChild(df, this);     
          return s;     
     });     
}
Copy code

13.html elements parentElement attribute

[Problem Description: parentElement] is elements of the property of the parent node, this property is supported only in IE, other browsers do not support.

[Compatible way]: parentNode property to get the parent node, such as:

//document.getElementById(id).parentElement, 

document.getElementById(id).parentNode, 

14 collections of objects

[Problem Description: IE] the collection object, such as forms, frames etc., can use () or [] gets a collection of objects, Safari, Chrome are also supported, such as

document.forms("formid") Or document.forms["FormID"]. But Firefox, can only use [] gets a collection of objects.

[Methods: the uniform use of compatible] [] gets a collection of objects, such as:

document.forms[0];

document.forms["formid"];

[Note]: all stored in the array object in access members, must take the [] index, such as the common XML document traversing, also need to change, as follows:

// xmldoc.documentElement.childNodes(1) 

xmldoc.documentElement.childNodes[1]

15.frame operation

[Problem Description:] in IE, Safari, Chrome, access to the frame object using the window object, you can use the ID and name attributes to obtain, such as

window.frameId;
window.frameName;

But in Firefox, you must use the frame object's name property to access to.

[Compatible way]:

(1)Access to frame objects: unified window.document.getElementById (frameId) to access the frame object.

(2)Switching frame content: unified window.document.getElementById (testFrame).Src=xxx.htm switch.

If you need the parameters in frame returns the parent window, you can use parent in frame to access the parent window. For example: parent.document.form1.filename.value=Aqing;

(3)Objects in the iframe page: $(" #frameid".Contents (.Find)) (" #html control ID")

(4)In the iframe page iframe: $("#frameid").contents().find("#frameid1").contents();

(5)In the iframe method or variable: $("#frameid")[0] .contentWindow.SaveFile("false", strRet, a);

16.insertAdjacentHTMLAndinsertAdjacentText

[Problem description]: insertAdjacentHTML method is inserted into the HTML code is more flexible than the innerHTML, the outerHTML property. It can be achieved in the front, a DOM element, the first child element behind the front, the last child element behind four position, insert the specified HTML. The DOM method is not W3C standard, W3C recently in the HTML5 draft to extend this method.

InsertAdjacentText is a method of inserting text is more flexible than the innerText, the outerText property. It can be achieved in the front, a DOM element, the first child element behind the front, the last child element behind four position, insert the specified text. The DOM method is not W3C standard so far, W3C HTML5 is not involved in this method.

InsertAdjacentHTML and insertAdjacentText can execute IE, Safari, Chrome, only the FireFox does not support,

[Compatible way]: using the following method is extended:

Copy code
if (typeof(HTMLElement) != "undefined") 
{
    HTMLElement.prototype.insertAdjacentElement = function(where, parsedNode) 
    {
        switch (where) 
        {
            case "beforeBegin":
                this.parentNode.insertBefore(parsedNode, this);
                break;
            case "afterBegin":
                this.insertBefore(parsedNode, this.firstChild);
                break;
            case "beforeEnd":
                this.appendChild(parsedNode);
                break;
            case "afterEnd":
                if (this.nextSibling)
                    this.parentNode.insertBefore(parsedNode, this.nextSibling);
                else
                    this.parentNode.appendChild(parsedNode);
                break;
        }
    }
    HTMLElement.prototype.insertAdjacentHTML = function(where, htmlStr) 
    {
        var r = this.ownerDocument.createRange();
        r.setStartBefore(this);
        var parsedHTML = r.createContextualFragment(htmlStr);
        this.insertAdjacentElement(where, parsedHTML);
    }

    HTMLElement.prototype.insertAdjacentText = function(where, txtStr) 
    {
        var parsedText = document.createTextNode(txtStr);
        this.insertAdjacentElement(where, parsedText);
    }
}         
Copy code

The children attribute on the 17.Html element

[Problem Description: children] is attribute HTML elements of sub nodes, only IE support, other browsers using childNodes.

[Methods: unified into compatible] take the child node with the attribute childNodes. Use the following method to expand the HTML element or attribute:

Copy code
if (typeof(HTMLElement) != "undefined") 
{
    HTMLElement.prototype.__defineGetter__("children",function(){ 
         var returnValue = new Object(); 
         var number = 0; 
         for(var i=0; i<this.childNodes.length; i++)
         { 
             if(this.childNodes[i].nodeType == 1)
             { 
                 returnValue[number] = this.childNodes[i]; 
                 number++; 
             } 
         } 
         returnValue.length = number; 
         return returnValue; 
    })
} 
Copy code

18.insertRow\inserCell 

[Problem description]: insertRow and insertCell is to insert a row in a table or column insertion method, use methods in IE are as follows

var nowTB = document.getElementById("tb1");
nowTR = nowTB.insertRow();
nowTD = nowTR.insertCell(); 

Safari, The Chrome can perform properly, but the insert row position is not the same as the IE default insert rows in table tail, Safari, Chrome default insert rows in the header; but call in FireFox will be in error.

[Compatible way]: the following methods can be called on all browsers, and insert rows locations are the end table, the difference is that the execution before passing a default value. Recommend the use of.

var nowTB = document.getElementById("tb1");

nowTR = nowTB.insertRow(-1);

nowTD = nowTR.insertCell(-1);

19.document.createElement

[Problem Description: IE] there are 3 ways you can create an element:

1 document.createElement("<input type=text>")

2 document.createElement("<input>")

3 document.createElement("input")

Safari, FireFox, Chrome supports only one way:

document.createElement("input");

document.setAttribute(name,value);

[Methods: using the method of unified] compatible with all browsers support, as follows:

document.createElement("input");

document.setAttribute(name,value);

20.The browserchildNodesThe similarities and differences

[Problem Description:] HTML code:

Copy code
<ul id="main">

<li>1</li>

<li>2</li>

<li>3</li>

</ul>

<input type=button value="click me!" onclick=

"alert(document.getElementById('main').childNodes.length)">
Copy code

With IE and other browsers, the result of IE is 3, and the other is 7.

IE is a complete tag as a node, While Safari, FireFox, Chrome in addition to the above cases, The end of a tag match ">" to start the next tag identifier "<" between content (except notes outside, Any text, including spaces, tabs, carriage returns) is a node, And this node also has their own unique attributes and values of nodeName="#text".

[Compatible way]: in practice, Safari, FireFox, Chrome in the traversal graph, for cycle in Riga

if(childNode.nodeName=="#text") continue;Or nodeType = = 1, then skip unwanted operation, make the program run more efficiently. You can also use the node.getElementsByTagName () to avoid.

21.document.getElementsByName

[Problem Description:] in only name elements attributes, no ID attribute, not obtain the DIV element in the IE, the browser can access other. There are the name and ID attributes, all browser can access to the DIV element.

[Compatible way]: use ID to get the.

22.trOperation

[Problem Description: IE] table in either innerHTML or appendChild insertion<tr>Have no effect, because in the IE browser, TR is read-only. While other browsers can this operation.

[Methods: the compatible]<tr>Added to table<tbody>Elements, as shown below:

Copy code
var row = document.createElement("tr");

var cell = document.createElement("td");

var cell_text = document.createTextNode("Insert content");

cell.appendChild(cell_text);

row.appendChild(cell);

document.getElementsByTagName("tbody")[0].appendChild(row);
Copy code

23.Remove nodesremoveNode() 

[Problem description]: appendNode can be used normally in IE and other browsers, but removeNode can only be used in IE. The function of the removeNode method is to delete a node, the syntax for node.removeNode (false) or node.removeNode (true), the return value is the removed node.

removeNode(false)Said simply delete node, then the child node of lifting this node as raw parent nodes, child nodes.

removeNode(true)Deletes the specified node and all its subordinate nodes. The removed node becomes isolated nodes, is no longer a child node and the node.

[Compatibility: compatible way] IE and other browsers are removeChild, go back to the parent node, the node is removed from the parent node to be removed.

// In order to use normal in IE and other browsers, and a layer of parent node, and then remove. 
node.parentNode.removeChild(node);

24.expression

[Problem Description: expression] expressions support style IE, but other browsers do not support, and IE versions may also this style is no longer supported, so that do not allow the use of. Below is a typical use case:

<div id="content"
 style='height:expression(document.body.offsetHeight-80)"></div>

[Compatible way]: remove the style settings, writes it to function, were performed in the page has finished loading and page size changes. The following:

Copy code
$(function(){
  $("#content").height($(document.body).height()-80);
})

$(window).resize(function(){
  $("#content").height($(document.body).height()-80);
});
Copy code

25.Cursor

[Problem description]: hand attribute Cursor IE only, other browsers do not have the effect, such as:

<div style="cursor:hand"></div>

[Methods: use pointer compatible] values, such as:

<div style="cursor: pointer"></div>

26.CSSThe issue of transparency

[Problem description]: IE support but transparent style that other browsers do not support the following:

<div style="filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=20);width:200px;height:200px;background-color:Blue">ddddd</div>

Other browsers support but transparent style of IE does not support the following:

<div style="opacity:0.2;width:200px;height:200px;background-color:Blue">ddddd</div>

[Methods: using compatible] "important!" to set the elements of style. Safari, FireFox, Chrome for "important!" will automatically priority analysis, however, IE will ignore. The following

<div style="filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=20);width:200px;height:200px;background-color:Blue;!important; opacity:0.2">ddddd</div>

27.pixelHeight\pixelWidth

[Problem description]: pixelHeight\pixelWidth is the height and width of style elements, usually get method:

obj.style.pixelWidth;

obj.style.pixelHeight;

IE, Safari, Chrome will support this style, the return value is an integer, FireFox does not support

[Compatible way]: all browsers support obj.style.height, but the value returned is the belt unit, such as "100px". Can use the following method to obtain:

parseInt(obj.style.height)

28.noWrap

[Problem description]: nowrap attribute is an attribute that was abandoned.

[Methods: using CSS compatible] rule white-space:nowrap instead of this attribute.

29.CSSThefloatAttribute

[Problem description]: Javascript access to most basic syntax for a given CSS value is: object.style.property, But the reserved word CSS property with the Javascript named in the same, Such as"float", "for", "class"Etc., Different browsers and different ways of writing.

Write it in IE:

document.getElementById("header").style.styleFloat = "left";

Write it in other browsers:

document.getElementById("header").style.cssFloat = "left";

[Compatibility: compatible way] is a judgment before writing, if the browser is IE:

if(jQuery.browser.msie){
    document.getElementById("header").style.styleFloat = "left";
}
else{
    document.getElementById("header").style.cssFloat = "left";
}

30.VisitlabelIn the labelfor

[Problem Description: the for attribute specifies] label and which form element binding. Write it in IE:

var myObject = document.getElementById("myLabel");

var myAttribute = myObject.getAttribute("htmlFor");

Write it in Firefox:

var myObject = document.getElementById("myLabel");

var myAttribute = myObject.getAttribute("for");

[Compatible way]: if the browser is IE:

Copy code
var myObject = document.getElementById("myLabel");
if(jQuery.browser.msie){
    var myAttribute = myObject.getAttribute("htmlFor");
}
else{
    var myAttribute = myObject.getAttribute("for");
}
Copy code

31.Access and setclassAttribute

[Problem Description:] also because class is the reason Javascript reserved words, these two browsers use different JavaScript methods to obtain this property.

All versions of IE IE8.0 prior to writing:

var myObject = document.getElementById("header");

var myAttribute = myObject.getAttribute("className");

For the IE8.0 and Firefox method:

var myObject = document.getElementById("header");

var myAttribute = myObject.getAttribute("class");

In addition, in the use of setAttribute () when setting the Class property of the two kinds of the browser, there is the same difference.

setAttribute("className",value);This approach applies to all versions of IE, IE8.0 before the note: IE8.0 does not support " className" property. SetAttribute (" class" value;,) for IE8.0 and Firefox.

[Compatible way]:

1 two are written on:

Copy code
1 //Set the header class for classValue
2 var myObject = document.getElementById("header");
3 
4 myObject.setAttribute("class","classValue");
5 
6 myObject.setAttribute("className","classValue");
Copy code

2.IE and FF support object.className, so you can write this:

var myObject = document.getElementById("header");

myObject.className="classValue";//Set the header class for classValue

3 first determine the type of browser, then according to the type of browser using the corresponding notation.

32.Object width height assignment problem

[Problem Description: obj.style.height = imgObj.height] invalid similar statements of non IE browser, must add'px'.

[Compatible way]: give elements of value is the unity of height and width, with 'PX', such as:

obj.style.height = imgObj.height + 'px';

33 the location of the mouse

[Problem description]: IE, even object has a x, but not pageX, y property, pageY property; Firefox, even object has a pageX, but not x, pageY property, y property; Safari, Chrome x, y property and the pageX, pageY all have.

[Compatible way]: the use of mX = event.x? Event.x: event.pageX; instead of. Complex but also consider the absolute position.

Copy code
function getAbsPoint(e){
    var x = e.offsetLeft, y = e.offsetTop;
    while (e = e.offsetParent) {
        x += e.offsetLeft;
        y += e.offsetTop;
    }
    alert("x:" + x + "," + "y:" + y);
}    
Copy code

34.event.srcElement

[Problem description]: IE, event object has a srcElement property, but not the target attribute; the other browsers, even object has a target property, but not the srcElement attribute.

[Compatible way]:

var obj = event.srcElement?event.srcElement:event.target;

35.About<input type="file">

(1) The controls in a safari browser without text box, only a "select file" button, all is not the onblur event, if in the <input type=" file" onblur=" alert (0); " > use need to do special processing.

(2) In the FF browser with <input type=" file" name=" file" > after uploading the files when file.value can only remove the file name without the file path, Cannot achieve preview effect, You can use document.getElementById (" pic".Files[0].getAsDataURL;) () take the path to the encrypted, This path can resolve only under FF.

(3) In the safari browser with <input type=" file" name=" file" > after uploading the files when file.value can only remove the file name without the file path, can not achieve the preview effect. The proposed path preview upload after use.

The 36.jquery object is not null

The jQuery object is empty judgment, using length to determine

$("#hidTitle").length>0

Analysis of IOS design pattern

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Nicholas at January 24, 2014 - 11:06 PM