DomHelper.js
上传用户:shuoshiled
上传日期:2018-01-28
资源大小:10124k
文件大小:14k
源码类别:

中间件编程

开发平台:

JavaScript

  1. /*!
  2.  * Ext JS Library 3.0.0
  3.  * Copyright(c) 2006-2009 Ext JS, LLC
  4.  * licensing@extjs.com
  5.  * http://www.extjs.com/license
  6.  */
  7. /**
  8.  * @class Ext.DomHelper
  9.  * <p>The DomHelper class provides a layer of abstraction from DOM and transparently supports creating
  10.  * elements via DOM or using HTML fragments. It also has the ability to create HTML fragment templates
  11.  * from your DOM building code.</p>
  12.  *
  13.  * <p><b><u>DomHelper element specification object</u></b></p>
  14.  * <p>A specification object is used when creating elements. Attributes of this object
  15.  * are assumed to be element attributes, except for 4 special attributes:
  16.  * <div class="mdetail-params"><ul>
  17.  * <li><b><tt>tag</tt></b> : <div class="sub-desc">The tag name of the element</div></li>
  18.  * <li><b><tt>children</tt></b> : or <tt>cn</tt><div class="sub-desc">An array of the
  19.  * same kind of element definition objects to be created and appended. These can be nested
  20.  * as deep as you want.</div></li>
  21.  * <li><b><tt>cls</tt></b> : <div class="sub-desc">The class attribute of the element.
  22.  * This will end up being either the "class" attribute on a HTML fragment or className
  23.  * for a DOM node, depending on whether DomHelper is using fragments or DOM.</div></li>
  24.  * <li><b><tt>html</tt></b> : <div class="sub-desc">The innerHTML for the element</div></li>
  25.  * </ul></div></p>
  26.  *
  27.  * <p><b><u>Insertion methods</u></b></p>
  28.  * <p>Commonly used insertion methods:
  29.  * <div class="mdetail-params"><ul>
  30.  * <li><b><tt>{@link #append}</tt></b> : <div class="sub-desc"></div></li>
  31.  * <li><b><tt>{@link #insertBefore}</tt></b> : <div class="sub-desc"></div></li>
  32.  * <li><b><tt>{@link #insertAfter}</tt></b> : <div class="sub-desc"></div></li>
  33.  * <li><b><tt>{@link #overwrite}</tt></b> : <div class="sub-desc"></div></li>
  34.  * <li><b><tt>{@link #createTemplate}</tt></b> : <div class="sub-desc"></div></li>
  35.  * <li><b><tt>{@link #insertHtml}</tt></b> : <div class="sub-desc"></div></li>
  36.  * </ul></div></p>
  37.  *
  38.  * <p><b><u>Example</u></b></p>
  39.  * <p>This is an example, where an unordered list with 3 children items is appended to an existing
  40.  * element with id <tt>'my-div'</tt>:<br>
  41.  <pre><code>
  42. var dh = Ext.DomHelper; // create shorthand alias
  43. // specification object
  44. var spec = {
  45.     id: 'my-ul',
  46.     tag: 'ul',
  47.     cls: 'my-list',
  48.     // append children after creating
  49.     children: [     // may also specify 'cn' instead of 'children'
  50.         {tag: 'li', id: 'item0', html: 'List Item 0'},
  51.         {tag: 'li', id: 'item1', html: 'List Item 1'},
  52.         {tag: 'li', id: 'item2', html: 'List Item 2'}
  53.     ]
  54. };
  55. var list = dh.append(
  56.     'my-div', // the context element 'my-div' can either be the id or the actual node
  57.     spec      // the specification object
  58. );
  59.  </code></pre></p>
  60.  * <p>Element creation specification parameters in this class may also be passed as an Array of
  61.  * specification objects. This can be used to insert multiple sibling nodes into an existing
  62.  * container very efficiently. For example, to add more list items to the example above:<pre><code>
  63. dh.append('my-ul', [
  64.     {tag: 'li', id: 'item3', html: 'List Item 3'},
  65.     {tag: 'li', id: 'item4', html: 'List Item 4'}
  66. ]);
  67.  * </code></pre></p>
  68.  *
  69.  * <p><b><u>Templating</u></b></p>
  70.  * <p>The real power is in the built-in templating. Instead of creating or appending any elements,
  71.  * <tt>{@link #createTemplate}</tt> returns a Template object which can be used over and over to
  72.  * insert new elements. Revisiting the example above, we could utilize templating this time:
  73.  * <pre><code>
  74. // create the node
  75. var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});
  76. // get template
  77. var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});
  78. for(var i = 0; i < 5, i++){
  79.     tpl.append(list, [i]); // use template to append to the actual node
  80. }
  81.  * </code></pre></p>
  82.  * <p>An example using a template:<pre><code>
  83. var html = '<a id="{0}" href="{1}" class="nav">{2}</a>';
  84. var tpl = new Ext.DomHelper.createTemplate(html);
  85. tpl.append('blog-roll', ['link1', 'http://www.jackslocum.com/', "Jack&#39;s Site"]);
  86. tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin&#39;s Site"]);
  87.  * </code></pre></p>
  88.  *
  89.  * <p>The same example using named parameters:<pre><code>
  90. var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
  91. var tpl = new Ext.DomHelper.createTemplate(html);
  92. tpl.append('blog-roll', {
  93.     id: 'link1',
  94.     url: 'http://www.jackslocum.com/',
  95.     text: "Jack&#39;s Site"
  96. });
  97. tpl.append('blog-roll', {
  98.     id: 'link2',
  99.     url: 'http://www.dustindiaz.com/',
  100.     text: "Dustin&#39;s Site"
  101. });
  102.  * </code></pre></p>
  103.  *
  104.  * <p><b><u>Compiling Templates</u></b></p>
  105.  * <p>Templates are applied using regular expressions. The performance is great, but if
  106.  * you are adding a bunch of DOM elements using the same template, you can increase
  107.  * performance even further by {@link Ext.Template#compile "compiling"} the template.
  108.  * The way "{@link Ext.Template#compile compile()}" works is the template is parsed and
  109.  * broken up at the different variable points and a dynamic function is created and eval'ed.
  110.  * The generated function performs string concatenation of these parts and the passed
  111.  * variables instead of using regular expressions.
  112.  * <pre><code>
  113. var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
  114. var tpl = new Ext.DomHelper.createTemplate(html);
  115. tpl.compile();
  116. //... use template like normal
  117.  * </code></pre></p>
  118.  *
  119.  * <p><b><u>Performance Boost</u></b></p>
  120.  * <p>DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead
  121.  * of DOM can significantly boost performance.</p>
  122.  * <p>Element creation specification parameters may also be strings. If {@link #useDom} is <tt>false</tt>,
  123.  * then the string is used as innerHTML. If {@link #useDom} is <tt>true</tt>, a string specification
  124.  * results in the creation of a text node. Usage:</p>
  125.  * <pre><code>
  126. Ext.DomHelper.useDom = true; // force it to use DOM; reduces performance
  127.  * </code></pre>
  128.  * @singleton
  129.  */
  130. Ext.DomHelper = function(){
  131.     var tempTableEl = null,
  132.      emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,
  133.      tableRe = /^table|tbody|tr|td$/i,
  134.      pub,
  135.      // kill repeat to save bytes
  136.      afterbegin = "afterbegin",
  137.      afterend = "afterend",
  138.      beforebegin = "beforebegin",
  139.      beforeend = "beforeend",
  140.      ts = '<table>',
  141.         te = '</table>',
  142.         tbs = ts+'<tbody>',
  143.         tbe = '</tbody>'+te,
  144.         trs = tbs + '<tr>',
  145.         tre = '</tr>'+tbe;
  146.     // private
  147.     function doInsert(el, o, returnElement, pos, sibling, append){
  148.         var newNode = pub.insertHtml(pos, Ext.getDom(el), createHtml(o));
  149.         return returnElement ? Ext.get(newNode, true) : newNode;
  150.     }
  151.     // build as innerHTML where available
  152.     function createHtml(o){
  153.     var b = "",
  154.      attr,
  155.      val,
  156.      key,
  157.      keyVal,
  158.      cn;
  159.         if(typeof o == 'string'){
  160.             b = o;
  161.         } else if (Ext.isArray(o)) {
  162.         Ext.each(o, function(v) {
  163.                 b += createHtml(v);
  164.             });
  165.         } else {
  166.         b += "<" + (o.tag = o.tag || "div");
  167.             Ext.iterate(o, function(attr, val){
  168.                 if(!/tag|children|cn|html$/i.test(attr)){
  169.                     if (Ext.isObject(val)) {
  170.                         b += " " + attr + "='";
  171.                         Ext.iterate(val, function(key, keyVal){
  172.                             b += key + ":" + keyVal + ";";
  173.                         });
  174.                         b += "'";
  175.                     }else{
  176.                         b += " " + ({cls : "class", htmlFor : "for"}[attr] || attr) + "='" + val + "'";
  177.                     }
  178.                 }
  179.             });
  180.         // Now either just close the tag or try to add children and close the tag.
  181.         if (emptyTags.test(o.tag)) {
  182.             b += "/>";
  183.         } else {
  184.             b += ">";
  185.             if ((cn = o.children || o.cn)) {
  186.                 b += createHtml(cn);
  187.             } else if(o.html){
  188.                 b += o.html;
  189.             }
  190.             b += "</" + o.tag + ">";
  191.          }
  192.         }
  193.         return b;
  194.     }
  195.     function ieTable(depth, s, h, e){
  196.         tempTableEl.innerHTML = [s, h, e].join('');
  197.         var i = -1,
  198.          el = tempTableEl;
  199.         while(++i < depth){
  200.             el = el.firstChild;
  201.         }
  202.         return el;
  203.     }
  204.     /**
  205.      * @ignore
  206.      * Nasty code for IE's broken table implementation
  207.      */
  208.     function insertIntoTable(tag, where, el, html) {
  209.     var node,
  210.          before;
  211.         tempTableEl = tempTableEl || document.createElement('div');
  212.        if(tag == 'td' && (where == afterbegin || where == beforeend) ||
  213.           !/td|tr|tbody/i.test(tag) && (where == beforebegin || where == afterend)) {
  214.             return;
  215.         }
  216.         before = where == beforebegin ? el :
  217.    where == afterend ? el.nextSibling :
  218.  where == afterbegin ? el.firstChild : null;
  219.         if (where == beforebegin || where == afterend) {
  220.          el = el.parentNode;
  221.      }
  222.         if (tag == 'td' || (tag == "tr" && (where == beforeend || where == afterbegin))) {
  223.         node = ieTable(4, trs, html, tre);
  224.         } else if ((tag == "tbody" && (where == beforeend || where == afterbegin)) ||
  225.             (tag == "tr" && (where == beforebegin || where == afterend))) {
  226.         node = ieTable(3, tbs, html, tbe);
  227.         } else {
  228.       node = ieTable(2, ts, html, te);
  229.         }
  230.         el.insertBefore(node, before);
  231.         return node;
  232.     }
  233.     pub = {
  234.     /**
  235.      * Returns the markup for the passed Element(s) config.
  236.      * @param {Object} o The DOM object spec (and children)
  237.      * @return {String}
  238.      */
  239.     markup : function(o){
  240.         return createHtml(o);
  241.     },
  242.     /**
  243.      * Inserts an HTML fragment into the DOM.
  244.      * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
  245.      * @param {HTMLElement} el The context element
  246.      * @param {String} html The HTML fragmenet
  247.      * @return {HTMLElement} The new node
  248.      */
  249.     insertHtml : function(where, el, html){
  250.         var hash = {},
  251.          hashVal,
  252.            setStart,
  253.          range,
  254.          frag,
  255.          rangeEl,
  256.          rs;
  257.         where = where.toLowerCase();
  258.         // add these here because they are used in both branches of the condition.
  259.         hash[beforebegin] = ['BeforeBegin', 'previousSibling'];
  260.         hash[afterend] = ['AfterEnd', 'nextSibling'];
  261.         if (el.insertAdjacentHTML) {
  262.             if(tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))){
  263.              return rs;
  264.             }
  265.             // add these two to the hash.
  266.             hash[afterbegin] = ['AfterBegin', 'firstChild'];
  267.             hash[beforeend] = ['BeforeEnd', 'lastChild'];
  268.             if ((hashVal = hash[where])) {
  269.          el.insertAdjacentHTML(hashVal[0], html);
  270.              return el[hashVal[1]];
  271.             }
  272.         } else {
  273.         range = el.ownerDocument.createRange();
  274.         setStart = "setStart" + (/end/i.test(where) ? "After" : "Before");
  275.         if (hash[where]) {
  276.       range[setStart](el);
  277.       frag = range.createContextualFragment(html);
  278.       el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling);
  279.       return el[(where == beforebegin ? "previous" : "next") + "Sibling"];
  280.         } else {
  281.         rangeEl = (where == afterbegin ? "first" : "last") + "Child";
  282.         if (el.firstChild) {
  283.         range[setStart](el[rangeEl]);
  284.         frag = range.createContextualFragment(html);
  285.                         if(where == afterbegin){
  286.                             el.insertBefore(frag, el.firstChild);
  287.                         }else{
  288.                             el.appendChild(frag);
  289.                         }
  290.         } else {
  291.               el.innerHTML = html;
  292.               }
  293.               return el[rangeEl];
  294.         }
  295.         }
  296.         throw 'Illegal insertion point -> "' + where + '"';
  297.     },
  298.     /**
  299.      * Creates new DOM element(s) and inserts them before el.
  300.      * @param {Mixed} el The context element
  301.      * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  302.      * @param {Boolean} returnElement (optional) true to return a Ext.Element
  303.      * @return {HTMLElement/Ext.Element} The new node
  304.      */
  305.     insertBefore : function(el, o, returnElement){
  306.         return doInsert(el, o, returnElement, beforebegin);
  307.     },
  308.     /**
  309.      * Creates new DOM element(s) and inserts them after el.
  310.      * @param {Mixed} el The context element
  311.      * @param {Object} o The DOM object spec (and children)
  312.      * @param {Boolean} returnElement (optional) true to return a Ext.Element
  313.      * @return {HTMLElement/Ext.Element} The new node
  314.      */
  315.     insertAfter : function(el, o, returnElement){
  316.         return doInsert(el, o, returnElement, afterend, "nextSibling");
  317.     },
  318.     /**
  319.      * Creates new DOM element(s) and inserts them as the first child of el.
  320.      * @param {Mixed} el The context element
  321.      * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  322.      * @param {Boolean} returnElement (optional) true to return a Ext.Element
  323.      * @return {HTMLElement/Ext.Element} The new node
  324.      */
  325.     insertFirst : function(el, o, returnElement){
  326.         return doInsert(el, o, returnElement, afterbegin, "firstChild");
  327.     },
  328.     /**
  329.      * Creates new DOM element(s) and appends them to el.
  330.      * @param {Mixed} el The context element
  331.      * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  332.      * @param {Boolean} returnElement (optional) true to return a Ext.Element
  333.      * @return {HTMLElement/Ext.Element} The new node
  334.      */
  335.     append : function(el, o, returnElement){
  336.     return doInsert(el, o, returnElement, beforeend, "", true);
  337.     },
  338.     /**
  339.      * Creates new DOM element(s) and overwrites the contents of el with them.
  340.      * @param {Mixed} el The context element
  341.      * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
  342.      * @param {Boolean} returnElement (optional) true to return a Ext.Element
  343.      * @return {HTMLElement/Ext.Element} The new node
  344.      */
  345.     overwrite : function(el, o, returnElement){
  346.         el = Ext.getDom(el);
  347.         el.innerHTML = createHtml(o);
  348.         return returnElement ? Ext.get(el.firstChild) : el.firstChild;
  349.     },
  350.     createHtml : createHtml
  351.     };
  352.     return pub;
  353. }();