我试图将鼠标悬停在一张图片上,然后让所有图片都变成我将鼠标悬停在上面的一张图片。我已经完成了。
当我鼠标移出时,我希望图像恢复正常,但我无法弄明白。
我正在尝试使用 rel 选择器,但在我现在的解决方案中,当我鼠标移出所有图像时,所有图像都采用第一张图像的 rel,而不是一切都恢复正常。
这是我的 HTML
<div id="container">
<header id="masthead"><h1>Swap All</h1></header>
<div id="stage">
<div id="gallery">
<img class="photo" rel="_images/image1.jpeg" src="_images/image1.jpeg" />
<img class="photo" rel="_images/image2.jpeg" src="_images/image2.jpeg" />
<img class="photo" rel="_images/image3.jpeg" src="_images/image3.jpeg" />
</div>
这是我的JS
function grabIt(){
var thisImageSrc = this.src;
$('.photo').attr('src', thisImageSrc);
}
function letItGo() {
var theRel = $('.photo').attr('rel');
$('#gallery img').attr( 'src', theRel);
console.log(theRel);
}
$('.photo').mouseover(grabIt);
$('.photo').mouseout(letItGo);
最佳答案
试试这个:
function letItGo() {
$('#gallery img').each(function() {
//option#1: pure JS
this.src = this.rel;
//option#2: jQuery (I'll leave this in as an option because the OP used this himself and might prefer it even though it is not necessary)
$(this).attr('src',$(this).attr('rel'));
});
}
明确一点:您只需要一个选项;如果您想使用纯 JS,请从代码中删除选项#2。反之亦然。
您尝试的方法不起作用,因为您仅将第一张照片的 rel-tag 存储到 var theRel
中。这行var theRel = $('#gallery img').attr('rel');
,即使匹配的元素再多,也只会选择第一个匹配的。
我的代码遍历所有匹配的元素,并且对于这些元素中的每一个,它使用自己的 rel-tag 来更改自己的 src-tag,使用 this
/$(这个)
。
关于jquery 将所有 src 更改为 rel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24111124/