如何将样式应用于 JavaScript 中的类?
我的身体中有多个需要相同样式的 div:
<div class="box"></div>
我有一个 javascript 可以计算浏览器窗口视口高度的高度。 我想将该高度应用于所有“box”类 div。
<script type="text/javascript">
var box = document.getElementsByClassName('box')[0];
var height = (window.innerHeight) ? window.innerHeight: document.documentElement.clientHeight;
box.style.height=(height)+'px';
</script>
这有效,但仅适用于一个 div,它不会使第二个“盒子”div 与前一个 div 具有相同的高度。如果我将方括号中的数字从 0 更改为 1,则会将高度应用于第二个 div。另外,如果我制作 javascript 的第二个副本,以便第一个脚本具有 [0] 和第二个 [1] ,它将高度应用于两个 div。我无法删除方括号,因为那样 JavaScript 就根本不起作用。我还尝试使用 getElementsByTagName 获取名称,但没有成功。
我怎样才能让这个javascript对所有具有“box”类的div应用相同的高度?或者还有另一种方法可以做我想做的事情吗?
I have multiple divs in my body which need the same style:
<div class="box"></div>
I have a javascript that calculates the height of the browser window viewport height.
I want to apply that height to all my "box" classed divs.
<script type="text/javascript">
var box = document.getElementsByClassName('box')[0];
var height = (window.innerHeight) ? window.innerHeight: document.documentElement.clientHeight;
box.style.height=(height)+'px';
</script>
This works, but only with one div, it doesn't make the second "box" div the same height as the previous. If I change the number in square brackets from 0 to 1 it applies the height to the second div. Also, if I make a second copy of the javascript so that the first script has [0] and the second [1] it applies the height to both divs. I can't delete the square brackets because then the javascript doesn't work at all. I have also tried to get the name with getElementsByTagName with no success.
How can I make this javascript apply the same height to all the divs with "box" class? Or is there another way to do what I try to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
尝试以下操作:
演示: http://jsfiddle.net/JRdHD/
try the following:
Demo: http://jsfiddle.net/JRdHD/