Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...