Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

javascript - How to change CSS property before element is created?

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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);

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...