我有一个 Logo 列表,我想用悬停效果来增强它。 (彩色标志 <-> 黑白标志)
我有以下标记:
var sourceToggle = function () {
var $this = $(this);
var newSource = $this.data('hover');
$this.data('hover', $this.attr('src'));
$this.attr('src', newSource);
}
$(function() {
$('img[data-hover]').each(function() {
new Image().src = $(this).data('hover');
}).hover(sourceToggle, sourceToggle);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="url">
<img src="http://lorempixel.com/200/200/sports/1/" data-hover="http://lorempixel.com/g/200/200/sports/1/">
</a>
这段代码到目前为止运行良好,但我想知道它是否是好的代码,或者我是否可以缩短它。
另外我想知道是否可以预加载悬停图像,因为有时加载速度不够快,我会看到闪烁。
最佳答案
我会删除“悬停”Javascript 部分,让 CSS 完成它的工作。运行 JS 只是为了准备字段,而不是让浏览器放松。
这是一个示例代码(也是一个 Fiddle ):
$(function () {
$('img[data-hover]').each(function () {
var thisImage = $(this);
var hoverSrc = thisImage.data('hover');
var hoverImage = $('<img class="bw_image" src="' + hoverSrc + '" />');
thisImage.after(hoverImage);
})
});
.hovering {
display: inline-block;
position: relative;
}
.hovering img {
display: block;
}
.bw_image {
position: absolute;
left: 0;
top: 0;
opacity: .01;
transition: opacity ease-in-out .2s;
}
.bw_image:hover {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class="hovering" href="url">
<img src="http://lorempixel.com/200/200/sports/1/" data-hover="http://lorempixel.com/g/200/200/sports/1/" />
</a>
<a class="hovering" href="url">
<img src="http://lorempixel.com/200/200/sports/2/" data-hover="http://lorempixel.com/g/200/200/sports/2/" />
</a>
<a class="hovering" href="url">
<img src="http://lorempixel.com/200/200/sports/3/" data-hover="http://lorempixel.com/g/200/200/sports/3/" />
</a>
关于javascript - 使用预加载在悬停时交换图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29011001/