JQuery:点击更改图片

时间:2013-12-10 10:11:41

标签: jquery image replace

希望有人在这里可以提供帮助,因为我花了几个小时搜索这个无济于事:/

基本上我需要的是有人已经创建的这个功能:Fiddle

$(function(){

  $("#big-image img:eq(0)").nextAll().hide();
  $(".small-images img").click(function(e){
    var index = $(this).index();
    $("#big-image img").eq(index).show().siblings().hide();
   });
});

但是当点击缩略图时,它也需要更改为不同的图像,以指示哪个图像处于活动状态。 (在我的例子中,小图像将是箭头)

我已经设法通过使用带有_on.png和_off.png的replace()来改变它,但是当单击一个新的时,我无法让它们更改回原来的png。

3 个答案:

答案 0 :(得分:1)

你可以添加/删除类:

DEMO

$(function(){
    $("#big-image img:eq(0)").nextAll().hide();
    $(".small-images img:eq(0)").addClass('selected');
    $(".small-images img").click(function(e){
        var index = $(this).index();
        $("#big-image img").eq(index).show().siblings().hide();
        $(this).addClass('selected').siblings().removeClass('selected');
    });
});

答案 1 :(得分:1)

添加两行额外的jQuery代码,以便在单击的缩略图上添加/删除类:

$(function () {
    $("#big-image img:eq(0)").nextAll().hide();
    $(".small-images span").click(function (e) {
        $("#big-image img").eq($(this).index()).show().siblings().hide();
        $(this).addClass("active").siblings().removeClass("active");
    }).eq(0).addClass("active");
});

...扔进一些CSS:

.small-images span {
    /* following three lines set the icon dimensions */
    display: inline-block;
    width: 16px;
    height: 16px;
    /* following two lines hide the text inside icon */
    text-indent: -1000px;
    overflow: hidden;
    /* following two lines display an icon from the "sprite" */
    background-image: url(sprite.png);
    background-position: 0 0;
    /* etc etc */
    cursor: pointer;
}
.small-images span:hover {
    background-color: orange;
}
.small-images span.active {
    background-color: purple;
}

Result

答案 2 :(得分:0)

你在找这个吗?

$(function(){
    $("#big-image img:eq(0)").nextAll().hide();
    $(".small-images img").click(function(e){
        var index = $(this).index();
        $(this).css('border','2px solid red').siblings().removeAttr('style');
        $("#big-image img").eq(index).show().siblings().hide();
    });
});

DEMO

相关问题