簡體   English   中英

jQuery:添加/刪除文本字符串到src屬性

[英]jQuery: Add/remove text string to src attribute

我試圖在mouseover將一串文本附加到圖像的src屬性,然后在mouseout上刪除該字符串。 現在我有一半工作:

使用Javascript

$('.singleSidebar .subnav img').mouseover(function(){
    $(this).attr('src', function(index, attr) {
    return attr.replace(/\.[^.]*$/, '_anim$&');
    });
});

我在其他地方找到了這個代碼,所以我不確定如何修改它以刪除mouseout上的字符串_anim

我建議只加載兩個圖像,然后只顯示你想要的圖像。 這一切都可以用CSS完成。

給一個圖像一個“動畫”類,另一個類“非動畫”。 添加此CSS以處理onhover更改:

    .singleSidebar .subnav img.animated,
    .singleSidebar .subnav img.nonanimated:hover
    {
        display: none;
    }
    .singleSidebar .subnav img.animated:hover,
    .singleSidebar .subnav img.nonanimated
    {
        display: block
    }

這樣可以更好地工作,因為瀏覽器會立即加載圖像,而不是當你將鼠標懸停時,它也有點清潔IMO

編輯啊,如果你需要他們開始玩懸停,那么你需要按照自己的方式去做。 嘗試這樣的事情:

$('.singleSidebar .subnav img').each(function(e){
    var src = $(this).attr('src');
    $(this).hover(function(){
      $(this).attr('src', src.replace('.gif', '_anim.gif'));
    }, function(){
      $(this).attr('src', src);
    });
  });

$(".singleSidebar .subnav img").hover(
  function () {
    $(this).attr('src', function(index, attr) {
      return attr.replace(/\.[^.]*$/, '_anim$&');
    });
  }, 
  function () {
    $(this).attr('src', function(index, attr) {     
        return attr.replace('_anim', ''); // or any other replace
    }); 
  }
);

有關更多信息,請訪問http://api.jquery.com/hover/

http://jsfiddle.net/dZ3c2/1/

var src;
$("img").hover(function() {
     src = $(this).attr("src");
    $(this).attr("src", "replacementsrc");
},function() {
     $(this).attr("src", src);
});​

應該能夠使用.mouseout並反轉替換。

$('.singleSidebar .subnav img').mouseout(function(){     
    $(this).attr('src', function(index, attr) {     
        return attr.replace(/_anim$/, '');     
    }); 
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM