dynamically add/remove style in javascript

后端 未结 3 913
执笔经年
执笔经年 2020-12-21 07:08

Is there a way in any browser to add/remove class names? For example, if I have a div with class names and I just want to remove/add \'name2\' is there a way to do that?

3条回答
  •  [愿得一人]
    2020-12-21 07:20

    There will be a standard way to do this. HTML5 introduces the classList property, which works like this:

    element.classList.add('foo');
    element.classList.remove('bar');
    if (element.classList.contains('bof'))
        element.classList.toggle('zot');
    

    Firefox 3.6 already has this feature and it's being worked on in WebKit.

    Here is a pure-JS implementation:

    // HTML5 classList-style methods
    //
    function Element_classList(element) {
        if ('classList' in element)
            return element.classList;
    
        return {
            item: function(ix) {
                return element.className.trim().split(/\s+/)[ix];
            },
            contains: function(name) {
                var classes= element.className.trim().split(/\s+/);
                return classes.indexOf(name)!==-1;
            },
            add: function(name) {
                var classes= element.className.trim().split(/\s+/);
                if (classes.indexOf(name)===-1) {
                    classes.push(name);
                    element.className= classes.join(' ');
                }
            },
            remove: function(name) {
                var classes= element.className.trim().split(/\s+/);
                var ix= classes.indexOf(name);
                if (ix!==-1) {
                    classes.splice(ix, 1);
                    element.className= classes.join(' ');
                }
            },
            toggle: function(name) {
                var classes= element.className.trim().split(/\s+/);
                var ix= classes.indexOf(name);
                if (ix!==-1)
                    classes.splice(ix, 1);
                else
                    classes.push(name);
                element.className= classes.join(' ');
            }
        };
    }
    
    // Add ECMA262-5 string trim if not supported natively
    //
    if (!('trim' in String.prototype)) {
        String.prototype.trim= function() {
            return this.replace(/^\s+/, '').replace(/\s+$/, '');
        };
    }
    
    // Add ECMA262-5 Array indexOf if not supported natively
    //
    if (!('indexOf' in Array.prototype)) {
        Array.prototype.indexOf= function(find, from /*opt*/) {
            for (var i= from || 0, n= this.length; i

    This does mean you have to write:

    Element_classList(element).add('foo');
    

    which is slightly less nice, but you'll get the advantage of the fast native implementation where avaialble.

提交回复
热议问题