0

这是几行用于动态创建 div 元素的 java 脚本代码。但我的疑问是在创建该元素之后,是否有任何快捷方式来分配多个 css 规则,而不是一次又一次地键入 (container.style)。

<script>
    (function(){
        window.onload = function(){
            var container = document.createElement('div');
            container.style.width = '500px';
            container.style.height = '200px';
            container.style.backgroundColor = 'red';
            container.style.margin = '0 auto';

            document.body.appendChild(container);
        }
    }());
</script>
4

4 回答 4

5

使用 CSS 类并将类分配给元素:

.MyClass {
   width: 500px;
   height: 200px;
   background-color: red;
   margin: 0 auto;
}

然后container.className = "MyClass";

于 2013-01-04T08:03:08.687 回答
1

您可以使用for循环来迭代对象,将属性一一应用到样式属性:

(function(){
    window.onload = function(){
        var container = document.createElement('div'),
            styles = {
                "width": "500px",
                "height": "200px",
                "backgroundColor": "red",
                "margin": "0 auto"
            },
            i;
        for (i in styles) {
            container.style[i] = styles[i];
        }

        document.body.appendChild(container);
    }
}());​

值得注意的是,这比原始代码长:-p 如果将for循环包装在另一个函数中并重复使用该函数,它可能会很有用。如果您发现自己反复需要这个,我强烈建议您包含jQuery(或ZeptoJS)并使用.css(…)来应用 CSS。jQuery 在应用属性时对属性进行了几次转换……它将属性名称中的连字符更改为正确的驼峰式大小写,进行更改以应用 IE 的正确属性或属性值等。它使编码更加容易,并且任何未来代码维护者也将从这种便利中受益。

于 2013-01-04T08:17:45.170 回答
0

您可以编写自己的css函数:

<script>
    (function(){
        window.onload = function(){
            var container = document.createElement('div');
            css(container,
                {'width': '500px',
                 'height': '200px',
                 'backgroundColor': 'red',
                 'margin': '0 auto'});

            document.body.appendChild(container);
        }

        function css(element, style){
            for(key in style){
                if(style.hasOwnProperty(key)){
                    element.style[key] = style[key];
                }
            }
        }
    }());
</script>

然后,您可以将该css()函数重新用于其他元素。

于 2013-01-04T08:26:04.650 回答
0

你可以这样使用

var container = document.createElement('div');
                container.setAttribute("id","div1");
                document.body.appendChild(container);

$("#div1").css({"width":"500px","height":"200px","background-color":"red"});

演示

于 2013-01-04T08:04:45.183 回答