简体   繁体   English

在JavaScript中设置div高度

[英]Setting a div height in JavaScript

I have three div s with the same class name that I want to alter the height and color of using JavaScript. 我有三个具有相同类名的div ,我想更改使用JavaScript的高度和颜色。 My code is breaking, not sure why. 我的代码坏了,不知道为什么。 I've looked at answers to similar problems on here and my code seems to be the same as the solutions. 我在这里已经找到了类似问题的答案,我的代码似乎与解决方案相同。

Any idea on where my code is breaking and how to fix it ? 关于我的代码在哪里中断以及如何解决的任何想法?

<HTML>
<head></head>
<body>
    <div class="bar"></div>
    <div class="bar"></div>
    <div class="bar"></div>
    <script>
        function altSize() {
            var bar = document.getElementsByClassName("bar");
            bar.style.height = 200px;
            bar.style.background = 'red';
        }
        altSize();
    </script>
</body>
</HTML>

It's breaking here: 在这里打破:

      bar.style.height=200px;

The reason is that 200px is not something you can assign in JS, it reads the 200 and doesn't know what to do with the px, it's not a valid number. 原因是200px不是您可以在JS中分配的东西,它读取200并且不知道该如何处理px,它不是有效数字。

Moreover, getElementsByClassName returns a NodeList and not a single element. 而且, getElementsByClassName返回一个NodeList而不是单个元素。

Fix it with 用修复

      for(var i=0;i<bar.length;i++){
           bar[i].style.height="200px";
      }

fiddle 小提琴

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

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