2012-05-25 94 views
0

我有一个小脚本在这里切换2个图像...它的工作原理就像如果你选择1st保持选中状态,如果你选择2nd - 1st消失并且正在选择2nd ...那样简单。jQuery在图像之间切换

$(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; 
} 

就请告诉我如何使用它的产品holder3,也许有一天,我需要更多的图像,所以请让我知道这是如何工作?非常感谢!

P.S我不知道什么jQuery的:d

回答

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/

+0

我已经加入$(文件)。就绪(函数(){你的脚本,而不是顶)};我已经添加了})和下面的})再次...它有点类似,但不是如果一个图像被选中,并点击另一个淡出它......它就像“Click = Selected,Click =再次选择,Click = One淡出并选择“所以它像2个图像一直被选中,而第三个正在淡出... – dvLden

+0

@NenaddvL只是让我明白:当你点击图像时,你想让图像淡出,图像在下一个产品持有者淡入,对吗? – Sampson

+0

好吧,我的英语不错,所以让我们这样做吧。 图片1,图片2,图片3. 页面被加载,我点击一个图片(例如图片2)。它按选定的方式淡入。 我改变主意,点击另一张图片...之前选择的图片(图片2)淡出,而我点击的新图片(淡入) – dvLden

0

你需要创建一个包含你通过(或者至少它们的ID)循环容器div的集合。像$(".theImage img:parent"),如果你不需要担心操纵单车秩序。然后在您的点击功能中,您可以使用$(this).parent().attr("id")中的ID查找当前的收集元素,然后获取它的索引。一旦你知道了索引,你就可以移动到集合中的下一个项目(或者如果你在最后,换到开头)并获得新的ID,将其设置为变量a的值。