2014-10-08 53 views
0

我正在使用jQuery在图像的开启和关闭悬停之间进行切换。这是我的代码。 HTML与attr配合使用与mouseover()和mouseout()(图像交换)

<img class="commentImg" src="images/comments.png" data-swap="images/comment_hover.png" alt=""> 

jQuery的

$(".commentImg").hover(function() { 
    var swap = $(this).attr("data-swap"); 
    $(this).attr('src', swap); 
}, 
function() { 
    var swap = $(this).attr("data-swap"); 
    $(this).removeAttr(swap); 
}); 

mouseover工作正常,但mouseout没有。你们能帮我吗?

回答

3

你需要将它存储

//store current src in a attribute 
 
$(".commentImg").attr('data-src', function() { 
 
    return $(this).attr('src'); 
 
}) 
 
$(".commentImg").hover(function() { 
 
    var swap = $(this).attr("data-swap"); 
 
    $(this).attr('src', swap); 
 
}, function() { 
 
    var src = $(this).attr("data-src"); 
 
    $(this).attr('src', src); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<img class="commentImg" src="//placehold.it/64/ff0000" data-swap="//placehold.it/64/ff00ff" /> 
 
<img class="commentImg" src="//placehold.it/64/00ff00" data-swap="//placehold.it/64/ffff00" /> 
 
<img class="commentImg" src="//placehold.it/64/0000ff" data-swap="//placehold.it/64/00ffff" />

+0

是啊,你是对的:) – 2014-10-08 04:31:14

+0

这工作。谢谢。 – 2014-10-08 04:31:55

0

我发现了另一个解决方案,它也完成的任务,也是有用的,如果你有很多图片。这是代码。可能有助于有人在那里,

HTML

<div class="large-8 columns commentWrap"> 
    <img class="commentImg" src="images/comments.png" data-swap="images/comment_hover.png" alt=""> 
    <p class="inline_cmt">Comments (3)</p> 
    </div> 
    <div class="large-2 columns inline_rply"> 
    <img class="replyImg" src="images/reply.png" data-swap="images/reply_hover.png" alt=""> 
    <p class="dash_reply">Reply</p> 
    </div> 
    <div class="large-2 columns reportWrap"> 
     <img class="reportImg" src="images/report.png" data-swap="images/report_hover.png" alt=""> 
     <p class="inline_rep">Report</p> 
    </div> 

jQuery的

var sourceSwap = function() { 
    var $this = $(this); 
    var newSource = $this.data('swap'); 
    $this.data('swap', $this.attr('src')); 
    $this.attr('src', newSource); 
    } 

$('.commentImg').hover(sourceSwap, sourceSwap); 
$('.replyImg').hover(sourceSwap, sourceSwap); 
$('.reportImg').hover(sourceSwap, sourceSwap);