我写了一个脚本,它的目标是停止显示图像一和二,同时允许图像三保持显示并移动到它们的位置。当我使用div Id而不是div类时,它可以正常工作,但我更喜欢使用div类来将元素分组,如下所示:
function myFunction() {
var y = document.getElementsByClassName("firstimage secondimage");
if (y.style.display === 'none') {
y.style.display = 'block';
} else {
y.style.display = 'none';
}
}
相比于这种方式(如果我选择包含更多元素来节省空间):
function myFunction() {
var x = document.getElementById("firstimage");
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
var y = document.getElementById("secondimage");
if (y.style.display === 'none') {
y.style.display = 'block';
} else {
y.style.display = 'none';
}
}
我认为仅仅将div id更改为div class,将#imagenumber更改为.imagenumber(除了我上面描述的javascript更改之外)就可以解决问题,但是当我这样做时,脚本停止工作。 我需要脚本以与我在下面粘贴的代码相同的方式运行,但使用div类而不是div Id。 请告诉我我错在哪里。
CSS:
#firstimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: green;
margin-top:20px;
color: white;
}
#secondimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: blue;
margin-top:20px;
color: white;
}
#thirdimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: red;
margin-top:20px;
color: white;
}
HTML:
<button onclick="myFunction()">Try me</button>
<div id="firstimage">
DIV element.
</div>
<div id="secondimage">
A second DIV element.
</div>
<div id="thirdimage">
A third DIV element.
</div>
Javascript:
function myFunction() {
var x = document.getElementById("firstimage");
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
var y = document.getElementById("secondimage");
if (y.style.display === 'none') {
y.style.display = 'block';
} else {
y.style.display = 'none';
}
}
getElementsByClassName
后的那一行上设置断点,然后检查变量y
。接着尝试检查y.style
。你应该能够很快地弄清楚发生了什么。或者,你可以在 Stack Overflow 上搜索“getElementsByClassName 不起作用”,因为这里有许多关于这个主题的问题,从六年前开始。 - user663031