如何在创建元素之前更改CSS属性?

时间:2012-12-28 13:10:10

标签: javascript html css

我必须在window.onloadbody.onload之前修改div的css。

<html>
    <head>
        <style type="text/css">
            html, body {
                width: 100%;
                height: 100%;
                padding: 0px;
                margin: 0px;
            }
            div {
                margin-left: auto;
                margin-right: auto;
            }
        <script>
            HTMLDivElement.prototype.style.marginTop = (window.innerHeight/2 - HTMLDivElement.scaleHeight/2) + "px";
        </script>
    </head>

    <body>
        <div>
        foo<br/>bar
        </div>
    </body>
</html>

3 个答案:

答案 0 :(得分:3)

我不知道这是否适用于所有浏览器,但您可以在style部分中添加新的head - 节点,如下所示:

var marginTop = ...;
var node = document.createElement("style");
node.setAttribute("rel", "stylesheet");
node.innerHTML = "div { margin-top: " + marginTop + "px; }";
document.head.appendChild(node);

显然,您的head元素必须存在才能生效。 我知道这很难看,我不能推荐使用它,但我认为这就是你想要的。

更新: 我找到了另一种方式,在我看来,因为你可以使用API​​,所以更好:

// insert a stylesheet if you don't have one
if (document.styleSheets.length == 0) {
    document.head.appendChild(document.createElement("style"));
}

var marginTop = ...;
var rule = "div { margin-top: " + marginTop + "px; }";
document.styleSheets[0].insertRule(rule);

有关详情,请访问http://www.w3.org/TR/DOM-Level-2-Style/css.html 我再次不知道所有浏览器是否支持此功能。

答案 1 :(得分:0)

在加载窗口之前,文档未加载到dom中。

所以从内存...... javascript无法编辑它。

你总是可以在onLoad之后编辑它,并且不应该注意到很多不同。

例如在jQuery中:

<script>
(function () {
    var divHeight = ($('div').height())/2,
        windowHeight = window.innerHeight/2;

    $('div').css('margin-top', windowHeight - divHeight);
}())
</script>

答案 2 :(得分:0)

当未加载元素时,您将如何找到它。这必须在服务器端完成。

BTW为什么你需要这种功能?