我正在尝试获取多个元素,这些元素组织在 3 个数组“上衣”、“下装”、“鞋子”下。
我知道我可以使用
抓取多个对象document.getElementsByClassName("class1 class2");
如何更改每个对象的样式,我当前的代码是:(我已经尝试了可见性和不透明度,但它不断收到未捕获的类型错误,因为 document.getelements.... 没有返回任何东西。
function filter() {
var this_id = event.target.id;
console.log(this_id);
if (this_id = "filtertops") {
document.getElementsByClassName("a4 a7 a11 a12 a8").style.visibility="hidden"; //not tops
document.getElementsByClassName("a1 a2 a3 a5 a9 a10 a14").style.visbility="visible"; // tops
}
else if (this_id = "filterbottoms") {
document.getElementsByClassName("a2 a3 a5 a10 a14 a8").style.opacity="0.4"; //not bottoms
document.getElementsByClassName("a1 a4 a7 a9 a11 a12").style.opacity="1"; //bottoms
}
else if (this_id = "filtershoes") {
document.getElementsByClassName("a1 a2 a3 a4 a5 a7 a9 a10 a11 a12 14").style.opacity="0.4"; //not shoes
document.getElementsByClassName("a8").style.opacity="1"; //shoes
}
我也尝试将它们分配给一个变量,然后使用 for 循环来更改每个对象的样式,但这也不起作用。
function filterbottoms() {
var nonbottom = document.getElementsByClassName("a2 a3 a5 a10 a14 a8");
var bottoms = document.getElementsByClassName("a1 a4 a7 a9 a11 a12");
for (i in bottoms)
{
i.style.visibility='visible';
}
for (i in nonbottom)
{
i.style.visibility='hidden';
}
}
最佳答案
您与for
很接近循环:
for (i in bottoms){
bottoms[i].style.visibility='visible';
}
应该<edit>
但不会</edit>
工作。每次迭代i
是下一个键,而不是下一个值。
但是你应该使用传统的for
而不是for..in
:
for (var i = 0; i < bottoms.length; i++){
bottoms[i].style.visibility='visible';
}
编辑:我推荐了传统的 for
循环,因为使用 for..in
通常不适用于数组或类似数组的对象,因为(取决于特定对象)它将迭代非数字属性。约瑟夫的评论证实了在这种情况下 for..in
由于这个原因肯定行不通。
关于javascript - 使用 javascript 更改多个图像的样式(不透明度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13046828/