如何在创建元素之前更改CSS属性? [英] How to change CSS property before element is created?
问题描述
我必须在 window.onload
和 body.onload
之前修改div的css。
I have to modify the div's css before the window.onload
, and body.onload
.
<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>
推荐答案
我不知道这是否适用于所有浏览器但你可以在你的头部
部分添加一个新的样式
-node,如下所示:
I don't know if that works in all browsers but you could append a new style
-node inside your head
section like this:
var marginTop = ...;
var node = document.createElement("style");
node.setAttribute("rel", "stylesheet");
node.innerHTML = "div { margin-top: " + marginTop + "px; }";
document.head.appendChild(node);
您的头
元素显然必须存在上班。
我知道这很丑,我不推荐使用这个,但我认为这是你想要的。
Your head
element must obviously exist for this to work.
I know it's ugly and I can't recommend using this but I think it's what you wanted.
更新:
我找到了另一种方式,在我看来,因为你可以使用的API更好:
UPDATE: I found another way, which in my opinion is better because of the API you can use:
// 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
再一次,我不知道所有浏览器是否都支持这一点。
For more information you may visit http://www.w3.org/TR/DOM-Level-2-Style/css.html Again I don't know if all browsers support this.
这篇关于如何在创建元素之前更改CSS属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!