简体   繁体   English

使用JavaScript更改div的宽度

[英]Using JavaScript to change width of div

I'm trying to use JavaScript to change the width of a div, but something's wrong with one part of my code. 我正在尝试使用JavaScript来更改div的宽度,但是我的代码的一部分出了点问题。 I think it's this part: 我认为这是这部分:

document.getElementById("div").style["width"] = width+"px";

I'm not sure what's wrong with it, so if you know, please let me know. 我不确定这是怎么回事,所以如果您知道,请告诉我。 Thanks. 谢谢。

<script>

function adapt (percentage) {

var width = percentage/100;
var width = window.innerWidth*width;

document.getElementById("div").style["width"] = width+"px";

}

adapt(80);

</script>


<style>

div {
border: 1px solid black;
}

</style>

<div id = 'div'> </div>

Your problem is that your Javascript appears before the element in the code. 您的问题是您的Javascript出现在代码中的元素之前。 Browsers process HTML documents top-down, so your Javascript gets executed before there's even an element to act upon. 浏览器从上到下处理HTML文档,因此您的Javascript甚至在没有要执行的元素之前就已执行。

You can either put the function call inside a window.onload wrapper, or put the <script> tag after the div . 您可以将函数调用放在window.onload包装器中,也可以将<script>标记放在div Usually, it is placed at the end of the <body> tag since all elements will have been processed by the browser at that point. 通常,它放置在<body>标记的末尾,因为所有元素将在此时被浏览器处理。

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

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