此方法假定图像具有相同的宽度和高度,并且具有固定的宽度/高度。
您在 html 中声明两个图像(普通图像和悬停图像)以“包含”div 开头,使该容器具有与图像相同的宽度和高度(在我的示例中,我使用了 300 像素 x 200 像素) .悬停图像最初隐藏在框架之外(在图像上使用绝对定位,在容器 div 上使用 CSS 使用 overflow: hidden),但在悬停时会滑入。
在此处查看演示:http://jsfiddle.net/2JSxK/7/
只需将那里的 HTML 替换为:
<div id="image-container">
<img class="pic" src="YOURIMAGENAME.jpg" />
<img class="hoverpic" src="YOURIMAGENAME_hover.jpg" />
</div>
以及带有图像宽度和高度的 CSS:
#image-container {
position: relative;
width: 300px; /* put your image width in pixels here */
height: 200px; /* put your image height in pixels here */
overflow: hidden;
}
#image-container img.pic {
position: absolute;
top: 0;
left: 0;
}
#image-container img.hoverpic {
position: absolute;
top: 200px; /* put your image height in pixels here */
left: 0;
}
在 jQuery 中相同,只需将 200 替换为您的图像高度(以像素为单位)两次:
$(document).ready(function() {
$('.pic').hover(
function () {
$('.hoverpic').animate({ "top": "-=200px" }, "slow" );
},
function () {
$('.hoverpic').animate({ "top": "+=200px" }, "slow" );
}
);
});
您还可以将"slow" 以上的速度更改为"fast" 或以毫秒为单位的数字,例如。 1000 将是一秒钟。取决于您希望滑动明显发生多快!
更正:悬停效果现在与容器而非单个图像相关联,因此当您移动鼠标时悬停图像不会消失。
在此处查看演示:http://jsfiddle.net/2JSxK/16/
新的 jQuery:
$(document).ready(function() {
$('#image-container').hover(
function () {
$('.hoverpic').animate({ "top": "-=200px" }, "slow" );
},
function () {
$('.hoverpic').animate({ "top": "+=200px" }, "slow" );
}
);
});
已编辑:为了说明页面上发生的动画不止一个,我稍微改变了结构/编写内容的方式(见下文 cmets)。
最新演示在这里:http://jsfiddle.net/2JSxK/17/