ITeye博客

insertAdjacentHTML与insertAdjacentText

deng131 · 2010-12-25 00:46 · dev theories · Web前端 · Markdown

insertAdjacentHTML是IE中的特有DOM方法但其不能应用于FIREFOX。

insertAdjacentHTML和insertAdjacentText insertAdjacentHTML方法:在指定的地方插入html标签语句。

原型:insertAdjacentHTML(swhere,stext) 参数: swhere:指定插入html标签语句的地方:              


 1.beforeBegin:插入到标签开始前 
 2.afterBegin:插入到标签开始标记后 
 3.beforeEnd:插入到标签结束标记前 
 4.afterEnd:插入到标签结束标记后 
 

为了兼容不同浏览器借用EXT中方法:


function insertHtml(where, el, html){      
     
    where = where.toLowerCase();      
    if(el.insertAdjacentHTML){      
     
        switch(where){      
            case "beforebegin":      
                el.insertAdjacentHTML('BeforeBegin', html);      
                return el.previousSibling;      
            case "afterbegin":      
                el.insertAdjacentHTML('AfterBegin', html);      
                return el.firstChild;      
            case "beforeend":      
                el.insertAdjacentHTML('BeforeEnd', html);      
                return el.lastChild;      
            case "afterend":      
                el.insertAdjacentHTML('AfterEnd', html);      
                return el.nextSibling;      
        }      
        throw 'Illegal insertion point -> "' + where + '"';      
    }      
                    
    var range = el.ownerDocument.createRange();      
    var frag;      
    switch(where){      
         case "beforebegin":      
            range.setStartBefore(el);      
            frag = range.createContextualFragment(html);      
            el.parentNode.insertBefore(frag, el);      
            return el.previousSibling;      
         case "afterbegin":      
            if(el.firstChild){      
                range.setStartBefore(el.firstChild);      
                frag = range.createContextualFragment(html);      
                el.insertBefore(frag, el.firstChild);      
                return el.firstChild;      
             }else{      
                el.innerHTML = html;      
                return el.firstChild;      
             }      
        case "beforeend":      
            if(el.lastChild){      
                range.setStartAfter(el.lastChild);      
                frag = range.createContextualFragment(html);      
                el.appendChild(frag);      
                return el.lastChild;      
            }else{      
                el.innerHTML = html;      
                return el.lastChild;      
            }      
        case "afterend":      
            range.setStartAfter(el);      
            frag = range.createContextualFragment(html);      
            el.parentNode.insertBefore(frag, el.nextSibling);      
            return el.nextSibling;      
    }      
    throw 'Illegal insertion point -> "' + where + '"';      
}     


参考: http://www.cnitblog.com/yemoo/archive/2007/10/11/34711.html http://ejohn.org/blog/dom-insertadjacenthtml/

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。