zoukankan      html  css  js  c++  java
  • insertAdjacentHTML方法示例

    添加HTML内容与文本内容以前用的是innerHTML与innerText方法,最近发现还有insertAdjacentHTML和insertAdjacentText方法,这两个方法更灵活,可以在指定的地方插入html内容和文本内容。
    insertAdjacentHTML方法:在指定的地方插入html标签语句

    原型:insertAdajcentHTML(swhere,stext)

    参数:

    swhere: 指定插入html标签语句的地方,有四种值可用:

    1.     beforeBegin: 插入到标签开始前

    2.     afterBegin:插入到标签开始标记之后

    3.     beforeEnd:插入到标签结束标记前

    4.     afterEnd:插入到标签结束标记后

    <!-- beforebegin -->
    <p>
    <!-- afterbegin -->
    foo
    <!-- beforeend -->
    </p>
    <!-- afterend -->
    

      

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    </head>
    
    <body>
    
    <div id="one">one</div> 
    
    <script type="text/javascript">
      var d1 = document.getElementById('one'); 
      d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
    </script>
    </body>
    </html>

    https://developer.mozilla.org/en-US/docs/Web/API/element.insertAdjacentHTML

    火狐8.0以下不支持该方法,咱们可以用一个函数去实现:

    if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement)
    {
         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)
         }
    }
    

      

  • 相关阅读:
    SEO网站优化之url友好设计
    mootools版本的lightbox实现(转载)
    利用ASP.NET2.0向导控件一步步建立与用户的交互基本概念
    ATLAS,一个越来越热的技术
    数据源控件与数据绑定控件的进一步简单讨论(1)
    ASP.NET2.0技术详解与应用实例源代码下载
    ASP.NET 2.0 Club Web Site Starter Kit 补丁
    ASP.NET 图片HTML元素的重载
    一个值得收藏的CSS站点网站
    ASP.NET2.0里的配置接口API
  • 原文地址:https://www.cnblogs.com/huanlei/p/3303179.html
Copyright © 2011-2022 走看看