Javascript YUI 讀碼日記之 YAHOO.util.Dom - Part.2 0_YUI.Ext相關

來源:互聯網
上載者:User
batch: function(el, method, o, override) {
    // 讓 el 始終為 HTMLElement
    el = (el && (el.tagName || el.item)) ? el : Y.Dom.get(el); 

    if (!el || !method) {
        return false;
    }

    //  確定返回的對象
    var scope = (override) ? o : window;

    // 看起來是個 HTMLElement 或者不是 Array
    if (el.tagName || el.length === undefined) {
        return method.call(scope, el, o);
    } 

    var collection = []; 
    for (var i = 0, len = el.length; i < len; ++i) {
        collection[collection.length] = method.call(scope, el[i], o);
    }

    return collection;
},小馬補充

batch 是 YUI Dom 庫的核心之一。它最大的意義在於,它讓 Dom 庫的其他大多方法
的第一個參數可以是一個 id / 元素對象 或 一組 id/元素對象,減少了迴圈的使用。在這裡可以找到 call 與 apply 的用法。在瞭解了 batch 以後,下來看 YUI.util.Dom 是怎麼使用這一方法的,一口氣看兩個函數

getStyle: function(el, property) {
    // toCamel 函數後面介紹
    property = toCamel(property);

    // 擷取節點的樣式
    var f = function(element) {
        return getStyle(element, property);
    };

    return Y.Dom.batch(el, f, Y.Dom, true);
},setStyle: function(el, property, val) {
    property = toCamel(property);

    // 設定節點的樣式
    var f = function(element) {
        setStyle(element, property, val);        
    };

    Y.Dom.batch(el, f, Y.Dom, true);
},有關這兩個函數的具體用法,可以看下相關的文檔。其實從參數上就很容易理解怎麼使用。看上面的兩個函數有利於理解 YAHOO.util.Dom.batch 的調用方式。

接下來,粗略看下 getXY

getXY: function(el) {
    var f = function(el) {
        // 確定元素是否“肉眼可見”
        if ( (el.parentNode === null || el.offsetParent === null ||
                this.getStyle(el, 'display') == 'none') && 
                            el != el.ownerDocument.body) {
            return false;
        }

        return getXY(el);
    };

    return Y.Dom.batch(el, f, Y.Dom, true);
},getX 與 getY 方法也是調用此函數,只是擷取傳回值的數組元素不一樣。由於瀏覽器的相容問題,提供給使用者的 YAHOO.util.Dom.getXY 也僅僅是判斷變數以後,再扔給最為複雜的內部 getXY 函數。

OK,留下太多的“懸念”了,下一期著重將它們解決。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.