我使用JS在悬停时更改图片...但是悬停的图片不能顺利加载。任何帮助表示赞赏。
<script type="text/javascript">
$( document ).ready(function() {
$('.img-grey').on({
mouseenter: function (e) {
var greysrc = $(this).attr('src');
var colorsrc = greysrc.replace("1.jpg", "2.jpg")
$(this).attr('src', colorsrc);
},
mouseleave: function (e) {
var colorsrc = $(this).attr('src');
var greysrc = colorsrc.replace("2.jpg", "1.jpg")
$(this).attr('src', greysrc);
}
})
});
</script>
&#13;
答案 0 :(得分:0)
或者,可以使用css解决此任务。检查css属性选择器https://www.w3schools.com/css/css_attribute_selectors.asp
您只需创建下一个html结构:
<div class="container">
<img src="1path-to-1.jpg" />
<img src="1path-to-2.jpg" />
</div>
<div class="container">
<img src="2path-to-1.jpg" />
<img src="2path-to-2.jpg" />
</div>
请参阅附件摘录
.container [src$="2.jpg"] {
display: none;
}
.container:hover [src$="1.jpg"] {
display: none;
}
.container:hover [src$="2.jpg"] {
display: inline;
}
.container {
float: left;
}
&#13;
<div class="container">
<img src="https://www.gravatar.com/avatar/8aecf6164a04433529bd7702f1b5f59a?s=128&d=identicon&r=PG&f=1&1.jpg" />
<img src="https://www.gravatar.com/avatar/f20fc11c3f294bdebe4351e7ca240678?s=128&d=identicon&r=PG&f=1&2.jpg" />
</div>
<div class="container">
<img src="https://www.gravatar.com/avatar/b8367b2f25ceee4d54595495b4e51312?s=128&d=identicon&r=PG&f=1&1.jpg" />
<img src="https://www.gravatar.com/avatar/f20fc11c3f294bdebe4351e7ca240678?s=128&d=identicon&r=PG&f=1&2.jpg" />
</div>
<div class="container">
<img src="https://www.gravatar.com/avatar/f20fc11c3f294bdebe4351e7ca240678?s=128&d=identicon&r=PG&f=1&1.jpg" />
<img src="https://www.gravatar.com/avatar/8aecf6164a04433529bd7702f1b5f59a?s=128&d=identicon&r=PG&f=1&2.jpg" />
</div>
&#13;
答案 1 :(得分:0)
如果要预加载图像,则应将其放入DOM或添加为背景属性。这是代码的修改版本,可在现有代码旁边添加隐藏的<img />
元素。我还没有运行它,但它应该可行
$( document ).ready(function() {
$('.img-grey').map(function () {
var temp = document.createElement('img');
temp.src = this.src.replace("1.jpg", "2.jpg");
temp.style.display = 'none';
$(this).parent().append(temp);
return this;
}).on({
mouseenter: function (e) {
var greysrc = $(this).attr('src');
var colorsrc = greysrc.replace("1.jpg", "2.jpg")
$(this).attr('src', colorsrc);
},
mouseleave: function (e) {
var colorsrc = $(this).attr('src');
var greysrc = colorsrc.replace("2.jpg", "1.jpg")
$(this).attr('src', greysrc);
}
})
});