简体   繁体   中英

javascript div container width resize problem

hej guys, I've got a problem trying to resize the width of a div container. I really don't know why it's not working... Thx for responding.

here's the code: It really works with Google Chrome. But with IE or Firefox just won't work.

<div id="div1" style="position:relative; background-color:#000000; width:100px; height:20px; color:#ffffff; text-align:center;">
    <div id="div2" style="position:absolute; background-color:#00ff00; left:0px; top:0px; bottom:0px; width:10px; text-align:right;">
    </div>
</div>

<script>
var container = document.getElementById("div1");
container.style.width = '300px';
</script>

Your call to document.getElementById() comes to early. Your element is not available at the DOM. Maybe Chrome adds the elements faster (?).

You should not rely on the position of your scripts in the source code. Use a onload() handler instead.

Replace the content of the script-tag with the following and it should work.

window.onload = function() {
    var container = document.getElementById("div1");
    container.style.height = '100px';
}

You need to put it all inside a body tag for the javascript to work (document.getElementById):

<body>

<div id="div1" style="position:relative; display:block; background-color:#000000; width:100px; height:20px; color:#ffffff; text-align:center;">
    <div id="div2" style="position:absolute; background-color:#00ff00; left:0px; top:0px; bottom:0px; width:10px; text-align:right;">
    </div>
</div>

<script>
var container = document.getElementById("div1");
container.style.width = '300px';
</script>

</body>

@hacksteak25 has the answer, but if you want to attach handlers to the load events (or most other events) for anything more than a quick hack, you should use the DOM/IE APIs to add event handlers:

function() init{
    var container = document.getElementById("div1");
    container.style.height = '300px';
}

if (window.addEventListener)
    window.addEventListener("load", init, false);
else if (window.attachEvent)
    window.attachEvent("onload", init);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM