简体   繁体   中英

Changing the style (opacity) of multiple images using javascript

I am trying to get multiple elements, that are organised under 3 arrays "tops", "bottoms", "shoes".

I know I can grab multiple objects using the

document.getElementsByClassName("class1 class2");

How do I change the style for each of those objects, my current code is: (I have tried both visibility and opacity, but it keep getting a uncaught type error because the document.getelements.... isn't returning anything.

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
    }

I tried assigning them to a variable as well and then a for loop to change the style of each object, but that didnt work either.

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';
        } 

}

You were close with the for loop:

for (i in bottoms){
    bottoms[i].style.visibility='visible';
}

should <edit> but won't </edit> work. On each iteration i is the next key, not the next value .

But you should use a conventional for rather than a for..in :

for (var i = 0; i < bottoms.length; i++){
    bottoms[i].style.visibility='visible';
}

EDIT: I recommended a conventional for loop because using for..in is generally not appropriate for arrays or array-like objects as (depending on the particular object) it will iterate over non-numeric properties. Joseph's comment confirms that in this case a for..in will definitely not work for that reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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