JavaScript实现无缝轮播图的示例代码

 更新时间:2022年07月08日 11:35:19   作者:不当菜菜  
这篇文章主要为大家详细介绍了如何利用JavaScript语言实现无缝轮播功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

花费一个下午从0到1实现的轮播图,当然还有很多需要改进的地方(欢迎提出需要改进的地方),等我再努力努力,将其封装成一个组件。

上效果

一、实现过程

1)首先实现基本布局

 <div class="carousel-container">
    //图片列表
    <div class="carousel-list"></div>
    //上一张
    <div class="carousel-arrow carousel-arrow-left">&lt</div>
    //下一张
    <div class="carousel-arrow carousel-arrow-right">&gt</div>
    //导航点
    <div class="indicator">
      <span class="active"></span>
      <span></span>
      <span></span>
    </div>
  </div>

2)主要样式

简单布局样式就不说了,主要讲如何将图片横向排列起来

先给容器设置相对定位,通过overflow将超出部分隐藏

.carousel-container {
      position: relative;
      width: 500px;
      height: 300px;
      /* overflow: hidden; */
      background-color: #ccc;
 }

然后图片列表设置相对定位和flex盒子,这样每一个滑块就横向排列成一排了

.carousel-container .carousel-list {
      position: relative;
      display: flex;
      height: 100%;
      width: 100%;
 }

左右滑动按钮通过绝对定位+transform的方式移动到两边,导航点也是一样,就不一一详说了

二、如何实现无缝呢 (重点来了)

思路:

1、先实现向后滚动无缝连接,将最后一张复制一份放到最前面,当滚动到最后一张时,再次滚动,将要滚动到第一张时,先取消过渡transition,瞬间跳到最前面复制的那张上,然后继续运行动画到第一张,这样看起来就无缝了

2、向前滚动无缝连接,思路同上,复制第一张图片放到最后,当滚动到第一张,再次滚动时,瞬间跳到最后复制的那张图片上,继续滚动到轮播图的最后一张上。

主要代码

先获取到dom元素,currentIndex是当前轮播到的图片下标

let currentIndex = 0;
const doms = {
      carouselList: document.querySelector('.carousel-list'),
      arrowLeft: document.querySelector('.carousel-arrow-left'),
      arrowRight: document.querySelector('.carousel-arrow-right'),
      indicator: document.querySelectorAll('.indicator span')
    }

先初始化dom,复制图片

// 复制第一张放最后,最后一张图片放第一张之前
    function init() {
      let lastImg = doms.carouselList.lastElementChild.cloneNode(true)
      let firstImg = doms.carouselList.firstElementChild.cloneNode(true)

      doms.carouselList.appendChild(firstImg)
      doms.carouselList.insertBefore(lastImg, doms.carouselList.firstElementChild)
      lastImg.style.position = 'absolute'
      lastImg.style.transform = 'translateX(-100%)'
    }
    //执行一下
    init()

实现到任意一张图片的方法

function moveTo(index) {
      doms.carouselList.style.transform = `translateX(-${index * 100}%)`
      doms.carouselList.style.transition = '.5s'

      // 去掉导航点选中效果
      let active = document.querySelector('.indicator span.active')
      active.classList.remove('active')
      // 添加选中效果
      doms.indicator[index].classList.add('active')
      currentIndex = index
    }

给导航点绑定点击跳转事件

// 给导航点添加事件
    doms.indicator.forEach((item, i) => {
      item.onclick = function () {
        moveTo(i);
      }
    })

给前后按钮绑上执行事件,判断边界图片,及时取消过渡效果,瞬间跳到复制的图片位置,调用moveTo到第一张或最后一张图片上。

let indicatorLength = doms.indicator.length;
    function preSlide() {
      if (currentIndex === 0) {
        doms.carouselList.style.transition = 'none'
        doms.carouselList.style.transform = `translateX(-${indicatorLength * 100}%)`
        doms.carouselList.clientHeight
        moveTo(indicatorLength - 1)
      } else {
        moveTo(currentIndex - 1)
      }
    }
    function nextSlide() {
      if (currentIndex === doms.indicator.length - 1) {
        doms.carouselList.style.transition = 'none'
        doms.carouselList.style.transform = 'translateX(100%)'
        doms.carouselList.clientHeight
        moveTo(0)
      } else {
        moveTo(currentIndex + 1)
      }
    }

    doms.arrowLeft.onclick = function () {
      preSlide();
    }

    doms.arrowRight.onclick = function () {
      nextSlide()
    }

最后使用定时器调用nertSlide方法就实现自动播放了

function start(time = 2000) {
      setInterval(() => {
        nextSlide()
      }, time)
    }
    start()

完整代码

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

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    .carousel-container {
      margin: 0 auto;
      position: relative;
      width: 500px;
      height: 300px;
      /* overflow: hidden; */
      background-color: #ccc;
    }

    .carousel-container .carousel-list {
      position: relative;
      display: flex;
      height: 100%;
      width: 100%;
    }

    .carousel-container .carousel-list .slide {
      flex: 0 0 100%;
      height: 100%;
      width: 100%;
    }

    .slide a {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
      width: 100%;
    }

    .slide a img {
      width: 100%;
    }

    .carousel-container .carousel-arrow {
      display: none;
      position: absolute;
      width: 36px;
      height: 36px;
      border-radius: 50%;
      color: white;
      text-align: center;
      line-height: 36px;
      cursor: pointer;

      background-color: rgba(31, 45, 61, .2);
    }

    .carousel-container:hover .carousel-arrow {
      display: block;
    }

    .carousel-container:hover .carousel-arrow:hover {
      background-color: rgba(31, 45, 61, .4);
    }

    .carousel-container .carousel-arrow-left {
      top: 50%;
      left: 2%;
      transform: translateY(-50%);
    }

    .carousel-container .carousel-arrow-right {
      top: 50%;
      right: 2%;
      transform: translateY(-50%);
    }

    .carousel-container .indicator {
      display: flex;
      position: absolute;
      left: 50%;
      top: 90%;
      transform: translateX(-50%)
    }

    .carousel-container .indicator span {
      margin: 2px 5px;
      padding: 3px;
      width: 5px;
      height: 5px;
      border: 1px solid white;
      border-radius: 5px;
    }

    .active {
      background-color: #fff;
    }
  </style>
</head>


<body>
  <div class="carousel-container">
    <div class="carousel-list">
      <div class="slide">
        <a href="">
          <img
            src="https://ts4.cn.mm.bing.net/th?id=OIP-C.kB-Ovasi0GW67-rmwnAcwAHaEo&w=316&h=197&c=8&rs=1&qlt=90&o=6&dpr=1.25&pid=3.1&rm=2">
        </a>
      </div>
      <div class="slide">
        <a href="">
          <img
            src="https://ts1.cn.mm.bing.net/th?id=OIP-C.QPH1IBosDYBqaU3O6wV3YAHaEo&w=316&h=197&c=8&rs=1&qlt=90&o=6&dpr=1.25&pid=3.1&rm=2"></a>
      </div>
      <div class="slide">
        <a href="">
          <img
            src="https://ts2.cn.mm.bing.net/th?id=OIP-C.P3NSGTdAYdyqy5zJpb5QXQHaEo&w=316&h=197&c=8&rs=1&qlt=90&o=6&dpr=1.25&pid=3.1&rm=2"
            alt=""></a>
      </div>
    </div>
    <div class="carousel-arrow carousel-arrow-left">&lt</div>
    <div class="carousel-arrow carousel-arrow-right">&gt</div>
    <div class="indicator">
      <span class="active"></span>
      <span></span>
      <span></span>
    </div>
  </div>
</body>

<script>
  window.onload = function () {
    const doms = {
      carouselList: document.querySelector('.carousel-list'),
      arrowLeft: document.querySelector('.carousel-arrow-left'),
      arrowRight: document.querySelector('.carousel-arrow-right'),
      indicator: document.querySelectorAll('.indicator span')
    }
    let currentIndex = 0;

    function moveTo(index) {
      doms.carouselList.style.transform = `translateX(-${index * 100}%)`
      doms.carouselList.style.transition = '.5s'

      // 去掉导航点选中效果
      let active = document.querySelector('.indicator span.active')
      active.classList.remove('active')
      // 添加选中效果
      doms.indicator[index].classList.add('active')
      currentIndex = index
    }

    // 给导航点添加事件
    doms.indicator.forEach((item, i) => {
      item.onclick = function () {
        moveTo(i);
      }
    })
    // 复制第一张放最后,最后一张图片放第一张之前
    function init() {
      let lastImg = doms.carouselList.lastElementChild.cloneNode(true)
      let firstImg = doms.carouselList.firstElementChild.cloneNode(true)

      doms.carouselList.appendChild(firstImg)
      doms.carouselList.insertBefore(lastImg, doms.carouselList.firstElementChild)
      lastImg.style.position = 'absolute'
      lastImg.style.transform = 'translateX(-100%)'
    }

    let indicatorLength = doms.indicator.length;
    function preSlide() {
      if (currentIndex === 0) {
        doms.carouselList.style.transition = 'none'
        doms.carouselList.style.transform = `translateX(-${indicatorLength * 100}%)`
        doms.carouselList.clientHeight
        moveTo(indicatorLength - 1)
      } else {
        moveTo(currentIndex - 1)
      }
    }
    function nextSlide() {
      if (currentIndex === doms.indicator.length - 1) {
        doms.carouselList.style.transition = 'none'
        doms.carouselList.style.transform = 'translateX(100%)'
        doms.carouselList.clientHeight
        moveTo(0)
      } else {
        moveTo(currentIndex + 1)
      }
    }

    doms.arrowLeft.onclick = function () {
      preSlide();
    }

    doms.arrowRight.onclick = function () {
      nextSlide()
    }

    function start(time = 2000) {
      setInterval(() => {
        nextSlide()
      }, time)
    }
    start()
    init()

  }
</script>

</html>

到此这篇关于JavaScript实现无缝轮播图的示例代码的文章就介绍到这了,更多相关JavaScript无缝轮播图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • javascript操纵OGNL标签示例代码

    javascript操纵OGNL标签示例代码

    这篇文章主要介绍了javascript 怎么操纵OGNL标签,需要的朋友可以参考下
    2014-06-06
  • 原生js实现表格循环滚动

    原生js实现表格循环滚动

    这篇文章主要为大家详细介绍了原生js实现表格循环滚动,每次滚动一行停顿,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-11-11
  • 原生JS实现响应式瀑布流布局

    原生JS实现响应式瀑布流布局

    本文给大家分享的是使用原生的javascript实现的响应式的瀑布流布局的方法和源码,非常的实用,有需要的小伙伴可以参考下。
    2015-04-04
  • 基于JS实现移动端访问PC端页面时跳转到对应的移动端网页

    基于JS实现移动端访问PC端页面时跳转到对应的移动端网页

    不想通过CSS自适应在PC端和移动端分别显示不同的样式,那么只能通过在移动端访问PC端网页时跳转到对应的移动端网页了,那么怎么跳转呢,网上也有很多文章说明,以下实现思路经过小编测试过,需要的朋友可以参考下
    2016-04-04
  • javascript弹出页面回传值的方法

    javascript弹出页面回传值的方法

    这篇文章主要介绍了javascript弹出页面回传值的方法,实例分析了由a1.html弹出的b1.html回传值的实现方法,非常具有实用价值,需要的朋友可以参考下
    2015-01-01
  • 使用cropper.js裁剪头像的实例代码

    使用cropper.js裁剪头像的实例代码

    最近小编在做一个裁剪头像的功能,下面小编把使用cropper.js裁剪头像的实例代码分享到脚本之家平台,需要朋友参考下吧
    2017-09-09
  • 原生js实现秒表计时器功能

    原生js实现秒表计时器功能

    这篇文章主要为大家详细介绍了原生js实现秒表计时器功能,可以开始、暂停、清除,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-02-02
  • js tr控制下面的tbody隐藏和显示

    js tr控制下面的tbody隐藏和显示

    这个问题弄了我几天没心思写程序,问了论坛很多网友才搞定的。
    2008-07-07
  • 基于bootstrap实现多个下拉框同时搜索功能

    基于bootstrap实现多个下拉框同时搜索功能

    这篇文章主要为大家详细介绍了基于bootstrap实现多个下拉框同时搜索功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-07-07
  • 全面解析JavaScript 中 null

    全面解析JavaScript 中 null

    null 是一种原始类型,表示有意不包含任何对象值,在这篇文章中,你将学习关于 JavaScript 中的 null 的一切: 它的含义,如何检测它,null 和 undefined 之间的区别,以及为什么大量使用 null 会造成代码维护困难等,需要的朋友可以参考下
    2022-09-09

最新评论