zoukankan      html  css  js  c++  java
  • 原型扩展的方法解决IE和Firefox的Js兼容问题

    if(!document.all){
    //textContent->text
        Element.prototype.__defineGetter__('text',function(){return this.textContent===undefined?this.text:this.nodeType?this.textContent:undefined;});
        Element.prototype.__defineSetter__('text',function(txt){this.textContent=txt;});

    //让firefox文本节点支持text属性
        Text.prototype.__defineGetter__('text',function(){return this.textContent===undefined?this.text:this.nodeType?this.textContent:undefined;});
        Text.prototype.__defineSetter__('text',function(txt){ this.textContent = txt;});
        
    //serializeToString->xml 只读
        Element.prototype.__defineGetter__('xml',function(){return this.nodeType?(new XMLSerializer()).serializeToString(this):null;});

    //addEventListener->attachEvent
        HTMLElement.prototype.attachEvent = function(ev, fn){
            ev = ev.toLowerCase();
            this.addEventListener(ev.indexOf('on')===0?ev.substr(2):ev, fn, false);
        };
    //removeEventListener->detachEvent
        HTMLElement.prototype.detachEvent = function(ev, fn){
            ev = ev.toLowerCase();
            this.removeEventListener(ev.indexOf('on')===0?ev.substr(2):ev,fn);
        };
        
        if(self!=top){ //为移动xWin定义事件,document为xWin下的document
          var doXwinMv=false; //用于修正移动xWin后其中的文本会被选中的问题
          document.addEventListener('mousedown', function(ev){ mouseOffset={x:ev.pageX, y:ev.pageY} });
          document.addEventListener('mousemove', function(ev){ top.mouseMove(ev); });
          document.addEventListener('mouseup', function(ev){ top.mouseUp(ev);if(window.getSelection() && doXwinMv) window.getSelection().collapseToStart(); doXwinMv=false;});
        }
        
        //修正firefox下xWin背景色为黑色的问题
        //if(!window.getComputedStyle(document.documentElement,null)['backgroundColor']) document.documentElement.style.backgroundColor = '#fff';
        //document.documentElement.style.backgroundColor = '#fff';

    //让firefox支持innerText属性
        HTMLElement.prototype.__defineGetter__("innerText",function(){
            var textRange = this.ownerDocument.createRange();
            textRange.selectNodeContents(this);
            return textRange.toString().replace(/ /g,'');
        });
        HTMLElement.prototype.__defineSetter__("innerText",function(str){
            this.textContent = str;
        });
        
    //修正firefox下firstChild lastChild获取到的是空白行文本节点的问题
        Element.prototype.__defineGetter__('firstChild',function(){
        var firstEleNode = firstNode = null;
        firstNode = this.childNodes[0];
        while (firstNode && firstNode.nodeType===3 && firstNode.nodeValue==' '){//若是空白行文本节点 则继续往后查找
            firstNode = firstNode.nextSibling;
        }
        firstEleNode = firstNode;
        return firstEleNode;
        });
        
        Element.prototype.__defineGetter__('lastChild',function(){
            var mIdx = this.childNodes.length-1;
            var lastNode = lastEleNode =null;
            lastNode = this.childNodes[mIdx];
            while(lastNode && lastNode.nodeType===3 && lastNode.nodeValue===' '){//若是空白行文本节点 继续往前查找
                lastNode = lastNode.previousSibling;
            }
            lastEleNode = lastNode;
            return lastEleNode;
        });
        
    //后台返回xml文档后,遍历节点会遍历到空白行文本节点 所以需要这个方法先删除空白行文本节点 属性节点也是子节点??
        Element.prototype.__defineGetter__('delEmptyLineNode',function(){ //注意:document文档节点没继承该属性 document.documentElemnt根节点继承了该属性
            function delEmpty(node){
                var chNodes=node.childNodes, re=/^s+$| | /m;
                for(var i=0, len=chNodes.length; i<len; i++){
                    if (chNodes[i] && chNodes[i].nodeType===1){
                        if(chNodes[i].childNodes.length===1){ //叶子节点
                            
                        }else{ //非叶子元素节点 递归
                            delEmpty(chNodes[i]);
                        }
                    }else if(chNodes[i] && chNodes[i].nodeType===3 && re.test(chNodes[i].nodeValue)){//空白文本节点
                        node.removeChild(chNodes[i]);
                        --i;
                    }
                }
            }
            delEmpty(this);
            return this;
        });
        
        
    //xmlNode.selectNodes()方法 只支持ie, 在当前xml节点下查找节点, Firefox下为Element原型定义同名属性
        Element.prototype.selectNodes = function(xpathStr){
            if(xpathStr.charAt(0)=='/') xpathStr="."+xpathStr;
            var snapshot = this.ownerDocument.evaluate(xpathStr, this, null, 7, null);
            var nodes = [];
            for(var i=0; i<snapshot.snapshotLength; i++){
                nodes.push(snapshot.snapshotItem(i));
            }
            return nodes;
        };
        
        Element.prototype.selectSingleNode = function(xpathStr){
            return this.selectNodes(xpathStr)[0];
        };
    //ie怪异模式下 可以node.children(2)这样获取第3个子节点,firefox或ie9等现代浏览器都不行,firefox修改同名属性children为children()方法来兼容
    //注:children重定义后,children[0]这样的写法将不可用
        Object.defineProperty(Element.prototype, 'children',{value:function(i){return this.delEmptyLineNode.childNodes[i];}, writable:true, enumerable:true, configurable:true});

    //(new DOMParser())).parseFromString(xmlStr, 'text/xml') --> loadXML
        XMLDocument.prototype.loadXML = function(xmlStr){
                return (new DOMParser()).parseFromString(xmlStr,'text/xml');
        };

    //让firefox支持insertAdjacentElement
        HTMLElement.prototype.insertAdjacentElement = function(sWhere, insEle){
            if(!insEle.nodeType) return;
            this.insertAdjacentHTML(sWhere,insEle.xml);
        };
    //让firefox支持ie事件对象的相关属性
    //-- returnValue --
        Event.prototype.__defineSetter__("returnValue", function(b){
            if(!b) this.preventDefault();
            return b
        });
    //-- cancelBubble --
        Event.prototype.__defineSetter__("cancelBubble", function(b){
            if(b) this.stopPropagation();
            return b;
        });
    //--- srcElement ---
        Event.prototype.__defineGetter__("srcElement", function(){
            var node = this.target;
            while(node.nodeType !== 1) node = node.parentNode;
            return node;
        });
    //--- fromElement ---
        Event.prototype.__defineGetter__("fromElement", function(){
            var node;
            if(this.type == 'mouseover'){ node = this.relatedTarget;}
            if(this.type == 'mouseout'){ node = this.target; }
            if(!node) return null;
            while(node.nodeType!=1){ node = node.parentNode; }
            return node;
        });
    //--- toElement ---
        Event.prototype.__defineGetter__("toElement", function(){
            var node;
            if(this.type == 'mouseover'){ node = this.target; }
            if(this.type == 'mouseout' ){ node = this.relatedTarget; }
            if(!node) return null;
            while(node.nodeType!=1){ node = node.parentNode; }
            return node;
        });

    //让firefox下table支持moveRow方法
        HTMLElement.prototype.moveRow = function(srcIdx, targetIdx){
            var re = /^(table|tbody|tfoot|thead)/i;
            if(!re.test(this.nodeName) || srcIdx === targetIdx) return;
            var pNode, srcR,targetR;
            pNode = this;
            if(this.nodeName.toLowerCase() === 'table') pNode = this.getElementsByTagName('tbody')[0]; //firefox 自动插入tbody
            //targetIdx<srcIdx 行往前面移 直接pNode.insertBefore()即可
            srcR = pNode.rows[srcIdx];
            targetR = pNode.rows[targetIdx];
            if(!srcR || !targetR) return; //索引范围以外 则返回
            targetRnext = pNode.rows[targetIdx+1] || null;
            if(targetIdx < srcIdx) pNode.insertBefore(srcR, targetR);
            if(targetIdx > srcIdx) pNode.insertBefore(srcR, targetRnext);
        };

    //让firefox下的styleSheet对象支持rules属性    
        CSSStyleSheet.prototype.__defineGetter__('rules', function(){return this.cssRules});

    //让firefox支持currentStyle 注意color样式值会转换为 rgb(233,22,22)的形式
        HTMLElement.prototype.__defineGetter__('currentStyle',function(){return window.getComputedStyle(this,null);});    

    //firefox createElementX
        HTMLDocument.prototype.createElementX = function (tag){
            var re=/^<.+>$/;
            if(re.test(tag)){ //<p ...></p> < ...>
                try{
                    var tmpDiv = this.createElement('div'); //临时div
                    tmpDiv.innerHTML = tag;
                    return tmpDiv.firstChild;
                }catch(err){alert(err.message);}
            }else{ // p, div...
                try{
                    return document.createElement(tag);
                }catch(e){alert(e.message)}
            }
        }
        
    }//For Firefox End

  • 相关阅读:
    设计模式研究
    requests模块请求常用参数的写法整理
    python程序打包exe文件
    爬虫响应信息乱码解决方式
    Vue-cli父子组件之间传参
    MYSQL事件隔离级别以及复读,幻读,脏读的理解
    [NOIP2009] 提高组 洛谷P1073 最优贸易
    [NOIP2009] 提高组 洛谷P1071 潜伏者
    [NOIP2009] 普及组
    洛谷P3386 【模板】二分图匹配
  • 原文地址:https://www.cnblogs.com/stephenykk/p/3222590.html
Copyright © 2011-2022 走看看