Changing CSS Values with Javascript

后端 未结 9 1410
借酒劲吻你
借酒劲吻你 2020-11-22 17:16

It\'s easy to set inline CSS values with javascript. If I want to change the width and I have html like this:

<
9条回答
  •  伪装坚强ぢ
    2020-11-22 17:54

    Please! Just ask w3 (http://www.quirksmode.org/dom/w3c_css.html)! Or actually, it took me five hours... but here it is!

    function css(selector, property, value) {
        for (var i=0; i

    The function is really easy to use.. example:

    Click Me!
    Or:
    Mouseover Me!
    Or:
    Click Me!

    Oh..


    EDIT: as @user21820 described in its answer, it might be a bit unnecessary to change all stylesheets on the page. The following script works with IE5.5 as well as latest Google Chrome, and adds only the above described css() function.

    (function (scope) {
        // Create a new stylesheet in the bottom
        // of , where the css rules will go
        var style = document.createElement('style');
        document.head.appendChild(style);
        var stylesheet = style.sheet;
        scope.css = function (selector, property, value) {
            // Append the rule (Major browsers)
            try { stylesheet.insertRule(selector+' {'+property+':'+value+'}', stylesheet.cssRules.length);
            } catch(err) {try { stylesheet.addRule(selector, property+':'+value); // (pre IE9)
            } catch(err) {console.log("Couldn't add style");}} // (alien browsers)
        }
    })(window);
    

提交回复
热议问题