我正在使用jQuery
在悬停时打开和关闭图像。这是我的代码。
HTML
<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
没有。你能帮助我吗?
答案 0 :(得分: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);
});
&#13;
<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" />
&#13;
答案 1 :(得分: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);