首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[分享]css中实现图片上下切换

发布于 2024-11-11 19:21:32
0
33

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);
}); 
评论
一个月内的热帖推荐
91云脑
Lv.1普通用户

62849

帖子

14

小组

291

积分

赞助商广告
站长交流