gpt4 book ai didi

javascript - 与 attr 混淆以与 mouseover() 和 mouseout()(图像交换)一起使用

转载 作者:太空宇宙 更新时间:2023-11-03 23:27:53 24 4
gpt4 key购买 nike

我正在使用 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 不行。你们能帮帮我吗?

最佳答案

你需要存储它

//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" />

关于javascript - 与 attr 混淆以与 mouseover() 和 mouseout()(图像交换)一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26249193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com