jQuery在图像之间切换

时间:2012-05-25 18:12:13

标签: jquery html css fadein fadeout

我在这里有一个小脚本可以在两个图像之间切换...就像你选择第一个它保持选中一样,如果你选择第二个 - 第一个正在淡出而第二个被选中......就像那样简单。

$(document).ready(function () {
    $(".theImage img").click(function () {
        var a = $(this).parent().attr("id") == "product-holder1" ? "product-holder2" : "product-holder1";
        console.log(a);
        $(this).fadeOut();
        $("#" + a + " img").fadeIn()
    })
})

我的问题是我不知道如何使用它来拍摄2张以上的照片? 假设我有id“product-holder3”,也许是“product-holder4”,那么如何在jquery代码中编写它,所以它仍然在选择哪一个之间切换?

HTML:

<div id="product-holder1" class="theImage">
  <img src="img/10-normal.png" />
</div>
<div id="product-holder2" class="theImage">
  <img src="img/25-normal.png" />
</div>
    <div id="product-holder3" class="theImage">
  <img src="img/50-normal.png" />
</div>

CSS

#product-holder1 {
    background: url("img/10-selected.png");
    background-repeat: no-repeat;
    height: 182px;
    width: 195px;
    position: absolute;
    top: 40px;
    left: 62px;
    cursor: pointer;
}
#product-holder2 {
    background: url("img/25-selected.png");
    background-repeat: no-repeat;
    height: 182px;
    width: 195px;
    position: absolute;
    top: 40px;
    left: 124px;
    cursor: pointer;
}
#product-holder3 {
    background: url("img/50-selected.png");
    background-repeat: no-repeat;
    height: 182px;
    width: 195px;
    position: absolute;
    top: 40px;
    left: 186x;
    cursor: pointer;
}

请告诉我如何将它用于产品持有者3,也许有一天我需要更多图片,所以请告诉我这是如何工作的?非常感谢!

P.S我对jQuery一无所知:D

2 个答案:

答案 0 :(得分:1)

这是基于以下评论中讨论的更新:

// Listen for the click event of our many containers
$(".theImage").on("click", function(){
   // In the event clicked, find image, fade slowly to .01 opacity
   $(this).find("img").fadeTo("slow",0).end()
     // Then, of siblings, find all images and fade slowly to 100% opacity
     .siblings().find("img").fadeTo("slow",1);           
});​

演示:http://jsfiddle.net/yvM8Z/2/

答案 1 :(得分:0)

您需要创建一个包含您正在循环的容器div(或至少它们的ID)的集合。如果您不需要担心操纵循环顺序,可以使用$(".theImage img:parent")之类的东西。然后在您的单击函数中,您可以使用$(this).parent().attr("id")中的id查找当前集合元素,然后获取它的索引。一旦你知道索引,就可以移动到集合中的下一个项目(如果你在最后,则换行到开头)并获得新的id,将其设置为变量a的值。 / p>