我有一个相当奇怪的问题,我似乎无法解决。我编写了一个代码,当某个元素具有这个特定的类名时我想使用它,所以我这样做了:
function slide() {
var box = document.getElementsByClassName('box');
if(box.style.maxHeight !== "100px") {
box.style.maxHeight = "100px";
box.style.opacity = "1";
} else {
box.style.maxHeight = "0";
box.style.opacity = "0";
}
return false;
}
HTML:
<h1 onclick="slide();"> Text </h1>
<div class="box">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est.
</p>
</div>
CSS:
.box {
max-height: 0;
}
我想我在这里遗漏了一些东西,但我不知道是什么。 有趣的是:当我使用getElementById
时,它有效!但是我想使用类名而这是行不通的。
我得到的错误是:
未捕获的TypeError:无法读取未定义的属性“maxHeight”
答案 0 :(得分:1)
获取元素按ClassName返回HTML集合。你需要在每个元素上分配它:
var boxes = document.getElementsByClassName('box');
for(box of boxes){
//work with elem
if(box.style.maxHeight !== "100px") {
box.style.maxHeight = "100px";
box.style.opacity = "1";
} else {
box.style.maxHeight = "0";
box.style.opacity = "0";
}
}
答案 1 :(得分:0)
var box = document.getElementsByClassName('box')[0];
答案 2 :(得分:-2)
getElementsByClassName
返回一个数组。它的项目具有style
属性,而不是数组本身。