1

我有以下代码,它在悬停时将我的图像名称从 image_off.jpg 更改为 image_on.jpg。我将它用于画廊。

    $(function(){
     $(".img-swap").hover(
          function(){this.src = this.src.replace("_off","_on");},
          function(){this.src = this.src.replace("_on","_off");
     });
});

但是,当我单击其中一张图像时,我希望图像名称保留在 image_on.jpg 上。这可能吗?当我单击另一个时,是否可以将其切换回关闭状态?

谢谢

4

4 回答 4

2

Hope this helps

it will work fine as you want with hover on and off and when you click the img it will be selected and will stay there and hover affect will not work

and when you click the next img all the rest which are selected will be removed and the hover affect will work on that

EDIT ** Changed the code Try it now

$(function(){
    $(".img-swap").hover(
    function(){
        if(!$(this).hasClass("selected")) {
            this.src = this.src.replace("_off","_on");
        }
    },
    function(){

        if(!$(this).hasClass("selected")) {
            this.src = this.src.replace("_on","_off");
        }

    }).click(function(){
        $('.img-swap').removeClass('selected').attr('src',this.src.replace("_on","_off"));;
        this.src = this.src.replace("_off","_on");
        $(this).addClass("selected").attr('src',this.src.replace("_off","_on"));
    });
});
于 2012-12-06T13:49:39.117 回答
1

您可以使用切换而不是悬停:

 $(".img-swap").toggle(
      function(){this.src = this.src.replace("_off","_on");},
      function(){this.src = this.src.replace("_on","_off");
 });

编辑:在点击时固定图像(防止它变回关闭),你可以这样做:

$(".img-swap").hover(
      function(){this.src = this.src.replace("_off","_on");},
      function(){if (!pinned) this.src = this.src.replace("_on","_off");
 }).click(){
      $(this).data('pinned': !($(this).data('pinned')||false));
 });
于 2012-12-06T13:16:19.870 回答
0

这是一些(未经测试的)代码:

 $(function(){
     $(".img-swap").hover(
      function(){
          this.src = this.src.replace("_off","_on");
      },
      function(){
          if(!this.hasClass("selected")) {
            this.src = this.src.replace("_on","_off");
          }
     }).click(function() {
         $(".img-swap.selected").removeClass("selected");
         this.addClass("selected");
     });
 });

它所做的是.selected为每个单击的元素添加一个类。悬停功能检查此类,并且仅在未选择图像时进行替换。

于 2012-12-06T13:27:00.977 回答
0

如果可以的话,您可以简单地为类添加 css 悬停事件

.img-swap:hover { src: image_on.jpg }

于 2012-12-06T13:27:55.493 回答