js實現css、addClass、removeClass和toggleClass

來源:互聯網
上載者:User

JQuery中擷取CSS樣式
css(name):訪問第一匹配元素的樣式屬性
css(name,value):在所有匹配的元素中,設定一個樣式屬性的值
css(properties):把一個“名/值對”對象設定為所有匹配元素的樣式屬性
css(name,function(index,value)):在所有匹配的元素中,設定一個樣式屬性的值
-------------------------------------------------------------------------------------
Javascript中擷取樣式的值       

       function css(obj, attr, value) {
            switch (arguments.length) {
                case 2:
                    if (typeof arguments[1] == "object") {    //大量設定屬性
                        for (var i in attr) obj.style[i] = attr[i]
                    }
                    else {    // 讀取屬性值
                        return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr]
                    }
                    break;
                case 3:
                    //設定屬性
                    obj.style[attr] = value;
                    break;
                default:
                    return "";
            }
        }
採用這種方式同樣實現了 JQuery的效果。
---------------------------------------------------------------------------------------
JQuery中有addClass,removeClass,toggleClass
addClass(class):為每個匹配的元素添加指定的類名
removeClass(class):從所有匹配的元素中刪除全部或者指定的類
toggleClass(class):如果存在(不存在)就刪除(添加)一個類
---------------------------------------------------------------------------------------
        function hasClass(obj, cls) {
            return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
        }

        function addClass(obj, cls) {
            if (!this.hasClass(obj, cls)) obj.className += " " + cls;
        }

        function removeClass(obj, cls) {
            if (hasClass(obj, cls)) {
                var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
                obj.className = obj.className.replace(reg, ' ');
            }
        }
採用這種方式同樣實現了 JQuery的效果。

相關文章

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.