简体   繁体   English

javascript div容器宽度调整大小问题

[英]javascript div container width resize problem

hej guys, I've got a problem trying to resize the width of a div container. 嘿,我在尝试调整div容器的宽度时遇到问题。 I really don't know why it's not working... Thx for responding. 我真的不知道为什么它不起作用...谢谢。

here's the code: It really works with Google Chrome. 代码如下:它确实适用于Google Chrome。 But with IE or Firefox just won't work. 但是,使用IE或Firefox将无法正常工作。

<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. 您对document.getElementById()调用来得很早。 Your element is not available at the DOM. 您的元素在DOM上不可用。 Maybe Chrome adds the elements faster (?). 也许Chrome可以更快地添加元素(?)。

You should not rely on the position of your scripts in the source code. 您不应该依赖脚本在源代码中的位置。 Use a onload() handler instead. 请改用onload()处理函数。

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标记中,以使javascript正常工作(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: @ hacksteak25有答案,但是如果您想将处理程序附加到load事件(或大多数其他事件)上,而不仅仅是快速的hack,那么您应该使用DOM / IE API添加事件处理程序:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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