2011-02-12 59 views
1

我有一个关于jQuery的问题。我有三个本质上相同的图像。不同的是,其中一个图像(我们称之为“活动”图像)是不同的颜色,而其他两个图像是相同的。jQuery改变图像onclick点击和其他人

这是一个视觉作品:我有一个“促销”横幅,其旁边有三个箭头图像。根据您点击的箭头图像,会显示不同的促销图片(共有三张促销图片 - 与箭头相同)。

我很喜欢它,如果我可以让“活动”箭头以一种颜色显示,而“非活动”箭头是另一种颜色。当我点击另一个箭头时,原来的“活动”一个因为“不活跃”而我刚刚点击的那个变为“活动”。我敢肯定,这是可以做到的,我只是不知道如何做到这一点:/

下面是我的工作的HTML:

<div class="rotation_container"> 
    <a class="rotator" id="rotator_1" href="#"><img class="cycle_icon" id="r1" src="images/promo/rotator_active.png" /></a> 
    <a class="rotator" id="rotator_2" href="#"><img class="cycle_icon" id="r2" src="images/promo/rotator_inactive.png" /></a> 
    <a class="rotator" id="rotator_3" href="#"><img class="cycle_icon" id="r3" src="images/promo/rotator_inactive.png" /></a> 
</div> 
+0

你可以使用类来做到这一点。点击箭头时,您将其全部设置为一个非活动类,除了被点击的类以外,您将其设置为活动类。 – JCOC611 2011-02-12 17:11:20

回答

2

像这样的事情可能与您当前的标记工作:

$('a.rotator').click(function() { 
    // Make all inactive 
    $('div.rotation_container img').attr('src', 'images/promo/rotator_inactive.png'); 

    // Make the one that was clicked active 
    $(this).find('img').attr('src', 'images/promo/rotator_active.png'); 
}); 

但真的,你应该通过CSS实现这一点。取出<img>元素和应用.active类活动锚:

<div class="rotation_container"> 
    <a class="rotator active" id="rotator_1" href="#"></a> 
    <a class="rotator" id="rotator_2" href="#"></a> 
    <a class="rotator" id="rotator_3" href="#"></a> 
</div> 

您可以通过CSS应用有效/无效的图像:

a.rotator { background:url(images/promo/rotator_inactive.png) } 
a.rotator.active { background:url(images/promo/rotator_active.png) } 

而且.click处理变得简单多了:

$('a.rotator').click(function() { 
    $('a.rotator.active').removeClass('active'); 
    $(this).addClass('active'); 
}); 
+0

我真的不敢相信我没有想到CSS方法。我一定会记住! – 2011-02-12 21:11:56

1

尝试类似下面的脚本:

$(document).ready(function(){ 
    $('.rotator').click(function(){ 
     $(this).find('img').attr('src', $(this).find('img').attr('src').replace('_inactive', '_active')); 

     $('.rotator:not(#'+$(this).attr('id')+') img').each(function(){ 
      $(this).attr('src', $(this).attr('src').replace('_active', '_inactive')); 
     }); 

     return false; 
    }); 
})(jQuery); 

1)如果 “.rotator” 被点击时,则:

2)中找到 “IMG” 的内部和替换 “_inactive” 与在src “_active”。

3)每隔 “IMG” 内部 “.rotator” 变成 “_inactive” 而不是 “_active”

4) “返回false;”使点击不滚动页面顶部

+0

这工作奇迹,谢谢! – 2011-02-12 21:13:04