简体   繁体   English

jQuery-循环浏览图像并隐藏所有未单击的图像

[英]jQuery - Loop through images and hide all but clicked image

Here's my HTML for my images: 这是我的图片HTML:

<img id="polaroid1" class="polaroid" onclick="fadeImages(this)" src="images/polaroid1.png">
<img id="polaroid2" class="polaroid" onclick="fadeImages(this)" src="images/polaroid2.png">
<img id="polaroid3" class="polaroid" onclick="fadeImages(this)" src="images/polaroid3.png">

After the user clicks any of these images, it calls the fadeImages() function. 用户单击任何这些图像后,它将调用fadeImages()函数。 Here's my JavaScript and jQuery: 这是我的JavaScript和jQuery:

function fadeImages(e) {
    var clickedImage = $(e).attr('id');

    $('img').each(function() {
        if($(this).attr('id') != clickedImage) {
            $('img').animate({opacity: 0}, 500);
        }
    });
 }

Basically, I want all images BUT the clicked image to fade out, but I don't know how to pass the clicked image ID into the 'each()' function. 基本上,我希望所有图像都能使单击的图像淡出,但是我不知道如何将单击的图像ID传递到'each()'函数中。 Any ideas? 有任何想法吗?

Bind a click event on each image which fades all of it's sibling elements. 在每个图像上绑定一个单击事件,使所有兄弟元素淡化。

$('img.polaroid').on('click', function(event) {
  $(this).siblings('.polaroid').animate({opacity: 0}, 500);
});
function fadeImages(e) {
    $('.polaroid').not(e).animate({opacity: 0}, 500);    
}

a nicer way is to remove onclick on your images and use the power of jQuery... 一种更好的方法是删除图像上的onclick并使用jQuery的功能...

Like this... 像这样...

$(function(){
    var $imgs = $('.polaroid');
    $imgs.click(function(){
         $imgs.not(this).animate({opacity: 0}, 500);
    });
})

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

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