CSS中实现图片上下切换,可以采用以下几种方式:
1. 利用CSS3的transition和transform属性
HTML代码:
<div class="container">
<img src="img1.jpg">
<img src="img2.jpg">
</div>
CSS代码:
.container {
position: relative;
width: 500px;
height: 300px;
overflow: hidden;
}
.container img {
position: absolute;
top: 0;
left: 0;
transition: all 1s ease;
}
.container img:nth-child(2) {
transform: translateY(300px);
}
.container:hover img:nth-child(1) {
transform: translateY(-300px);
}
.container:hover img:nth-child(2) {
transform: translateY(0);
} 2. 利用CSS3的animation属性
HTML代码:
<div class="container">
<img src="img1.jpg">
<img src="img2.jpg">
</div>
CSS代码:
.container {
position: relative;
width: 500px;
height: 300px;
overflow: hidden;
}
.container img {
position: absolute;
top: 0;
left: 0;
animation: slideUp 1s linear infinite;
}
.container img:nth-child(2) {
animation-delay: 1s;
}
@keyframes slideUp {
0% {
transform: translateY(0);
}
50% {
transform: translateY(-300px);
}
100% {
transform: translateY(0);
}
} 3. 利用jQuery的animate()方法
HTML代码:
<div class="container">
<img src="img1.jpg">
<img src="img2.jpg">
</div>
CSS代码:
.container {
position: relative;
width: 500px;
height: 300px;
overflow: hidden;
}
.container img {
position: absolute;
top: 0;
left: 0;
}
.container img:nth-child(2) {
top: 300px;
}
JS代码:
$(function() {
setInterval(function() {
$('.container img:first-child').animate({
top: '-300px'
}, 1000, function() {
$(this).appendTo('.container').css('top', '0');
});
$('.container img:nth-child(2)').animate({
top: '0'
}, 1000);
}, 3000);
});