Alter CSS class attributes with javascript?

后端 未结 1 1142
醉梦人生
醉梦人生 2020-12-17 01:43

I have a CSS class defined, call it:


where

相关标签:
1条回答
  • 2020-12-17 02:38

    I think this is what you want:

    <script>
    var style;
    function changeFoo(left, top) {
        if(typeof style == 'undefined') {
            var append = true;
            style = document.createElement('style');
        } else {
            while (style.hasChildNodes()) {
                style.removeChild(style.firstChild);
            }
        }
        var head = document.getElementsByTagName('head')[0];
        var rules = document.createTextNode(
            '.Foo { left: ' + left + 'px; top: ' + top + 'px; }'
        );
    
        style.type = 'text/css';
        if(style.styleSheet) {
            style.styleSheet.cssText = rules.nodeValue;
        } else {
            style.appendChild(rules);
        }
        if(append === true) head.appendChild(style);
    }
    </script>
    

    This code was modified from an answer provided in this question which is very similar to what you asked. Whenever you need to change the position of all .Foo elements, you can just call changeFoo(newLeftValue, newTopValue); - the first time around it will create the <style> element and add it to the <head> of the document. Subsequent calls will just empty the <style> element that was already added and add the new rule.

    0 讨论(0)
提交回复
热议问题