使用纯css实现轮播效果

16 篇文章 0 订阅
7 篇文章 0 订阅

属性介绍

制作网页尤其是电商类、网站主页等都会遇到轮播图的需求,以往实现轮播图,若不借助第三方插件如swiper等,就需要自行手动实现轮播效果,一大堆的js代码,现在可以使用css实现简单的轮播效果(不包括循环滚动、跳转等)。

scroll-snap-type

scroll-snap-type CSS 属性定义在滚动容器中的一个临时点(snap point)如何被严格的执行。
具体语法,可以参考MDN中的介绍:
scroll-snap-type

scroll-snap-align

scroll-snap-align MDN地址,目前没有中文版本,此属性的作用是在滚动时确定滚动元素与容器元素之间的边界位置,

scroll-snap-align: [ none | start | end | center ]{1,2}

例如,center就代表滚动元素的中心点与容器的中心点药保持位置统一。
效果展示:
css实现轮播

代码实现

完整代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>css实现轮播效果</title>
  <style>
    html,
    body {
      height: 100%;
    }

    * {
      padding: 0;
      margin: 0;
    }

    .swiper {
      width: 100%;
      height: 100%;
      overflow: auto;
      white-space: nowrap;
      scroll-snap-type: x mandatory;
      scroll-snap-stop: always;
    }

    .swiper__item {
      height: 100%;
      width: 100%;
      scroll-snap-align: center;
      display: inline-block;
    }

    .swiper__item--red {
      background-color: red;
    }

    .swiper__item--green {
      background-color: green;
    }

    .swiper__item--yellow {
      background-color: yellow;
    }

    .swiper__item--pink {
      background-color: pink;
    }
  </style>
</head>
<div class="swiper">
  <div class="swiper__item swiper__item--red"></div>
  <div class="swiper__item swiper__item--green"></div>
  <div class="swiper__item swiper__item--yellow"></div>
  <div class="swiper__item swiper__item--pink"></div>
</div>

<body>

</body>

</html>

结尾

  借助上述属性,可以实现简单的轮播效果,避免了引入第三方插件或者自行实现效果是的大量代码,但是此效果只能应对简单的轮播需求,涉及循环播放、点击跳转等,还需要自行实现。

tips:
    点滴记录,汇聚江河

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值