我试图将鼠标悬停在一张图片上,然后将所有图片转到我要悬停的一张图片上。我已经完成了。
当我将鼠标移出时,我希望图像恢复正常,但我无法弄清楚。
我正在尝试使用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,请从代码中删除option#2。反之亦然。
您尝试的操作不起作用,因为您仅将第一张照片的rel-tag存储到var中theRel
。var theRel = $('#gallery img').attr('rel');
即使有更多匹配的元素,该行也只会选择第一个匹配项。
我的代码循环在那场比赛的所有元素,这些元素中的每一个,它使用自己的REL-标签来改变自己的SRC标签,使用this
/ $(this)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句