1

HTML:

<div class="slide">
  <div class="left">
    <img src="img-lg.png" class="image1" />
  </div>
  <div class="thumbs">
    <img src="img-sm.png" />
  </div>
</div>

<div class="slide">         
  <div class="left">
    <img src="anotherimg-lg.png" class="image1" />
  </div>
  <div class="thumbs">
    <img src="anotherimg-sm.png" />
  </div>    
</div>

Jquery:

var originalContent = $('.left').html();
$("div.thumbs img").hover(function(){
  var largesrc = $(this).attr("src").replace("sm","lg");
  $(".left").html('<img src="' + largesrc 
    + '" width="560" height="377" class="largeimage" />');
}, function() {
  $(".left").html(originalContent);
});

ホバー時に大きな画像を小さな画像に置き換えてから、元の画像に戻します。これは正常に機能しますが、複数のインスタンスで機能させる方法がわかりません。

2番目のスライドセットでは、左の画像が元の最初の左の画像に置き換えられ、2番目の画像には置き換えられません。

4

2 に答える 2

4

どうですか

$("div.thumbs img").hover(function(){
        $(this).closest('.slide').find('.left img').attr({
            src: this.src.replace("sm","lg"),
            width: 560,
            height: 377,
            'class': 'largeimage'
        });
}, 
function() {
        var img = $(this).closest('.slide').find('.left img');
        img.attr({src: img[0].src.replace("lg","sm")})
        .removeAttr('width height class');
});

srcここでは、dom構造を変更せずに、image要素のプロパティを交換します。

デモ

于 2012-11-06T05:58:45.123 に答える
0
$("div.thumbs img").hover(function(){
  var $this = $(this);

  // find the containing .slide, then find .left within that
  var left = $this.closest('.slide').find('.left');

  // store the original content as "data" on `left`, so
  // we can get it easily in the future
  left.data('originalContent', left.html());

  var largesrc = $this.attr("src").replace("sm","lg");
  left.html('<img src="' + largesrc 
    + '" width="560" height="377" class="largeimage" />');
}, function() {
  var $this = $(this);
  var left = $this.closest('.slide').find('.left');

  // fetch the "data" we stored earlier, and restore it
  left.html(left.data('originalContent'));
});

ライブの例はこちらから入手できます。

于 2012-11-06T06:09:55.290 に答える