原生js--insertAdjacentHTML

insertAdjacentHTML是IE浏览器提供向DOM中插入html字符串的方法,字符串会自动生成在DOM树中。javascript

其调用方式为elem.insertAdjacentHTML( position, htmlStr )html

elem 向哪一个DOM的标签出插入字符串java

position 有四个选项 "beforeBegin" "afterEnd" "afterBegin" "beforeEnd"分别指在elem的开始标签以前、结束标签以后、开始标签以后、结束标签以前插入htmlStr浏览器

htmlStr 字符串(不是DOM元素)app

如下是在《javascript权威指南》中摘抄的,从新封装并重命名了该功能的Insert对象。并同时解决insertAdjacentHTML的浏览器兼容性问题this

/**
 * 在开始或结束标签的先后插入html字符串
 * before 在开始标签以前插入html字符串
 * after 在结束标签以后插入html字符串
 * atStart 在开始标签以后插入字符串
 * atEnd 在结束标签以前插入字符串
 */
Insert = ( function(){
    if( document.createElement( "div" ).insertAdjacentHTML ){
        return {
            // e element, h html
            before : function( e, h ){
                // beforebegin大小写都可, h {string} html字符串或text都可
                e.insertAdjacentHTML( "beforebegin", h );
            },
            after : function( e, h ){
                e.insertAdjacentHTML( "afterend", h );
            },
            atStart : function( e, h ){
                e.insertAdjacentHTML( "afterbegin", h );
            },
            atEnd : function( e, h ){
                e.insertAdjacentHTML( "beforeEnd", h );
            }
        };
    }

    function fragment( html ){
        var tmpDiv = document.createElement( "div" ),
            frag = document.createDocumentFragment();
        tmpDiv.innerHTML = html;
        while( tmpDiv.firstChild ){
            frag.appendChild( tmpDiv.firstChild );
        }
        return frag;
    }

    var Insert = {
        before : function( e, h ){
            e.parentNode.insertBefore( fragment( h ), e );
        },
        after : function( e, h ){
            // 当e.nextSibling为空时,insertBefore方法会将frament(h)插入到最后
            e.parentNode.insertBefore( fragment( h ), e.nextSibling );
        },
        atStart : function( e, h ){
            e.insertBefore( fragment( h ), e.firstChild );
        },
        atEnd : function(){
            e.appendChild( fragment( h ) );
        }
    };

    // 同时解决insertAdjacentHTML的兼容性问题
    Element.prototype.insertAdjacentHTML = function( pos, html ){
        switch( pos.toLowerCase() ){
            case "beforebegin" : return Insert.before( this, html );
            case "afterend" : return Insert.after( this, html );
            case "afterbegin" : return Insert.atStart( this, html );
            case "beforeend" : return Insert.atEnd( this, html );
        }
    };

    return Insert;
}() );prototype

相关文章
相关标签/搜索