问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Document

创作时间:
作者:
@小白创作中心

Document

引用
CSDN
1.
https://m.blog.csdn.net/2301_81253185/article/details/143465702

轮播图是网页开发中常见的交互元素,能够以动态的方式展示多张图片或内容。本文将详细介绍如何使用HTML、CSS和JavaScript实现一个功能丰富的轮播图效果,包括左右箭头切换、小圆点导航、鼠标悬停停止等功能。

轮播图功能

  • 轮播图会有一个向左移动的视野效果
  • 点击右边图片会向左更新
  • 点击左边图片会向右更新
  • 点击右边箭头会向左更新
  • 点击左边箭头会向右更新
  • 使用鼠标在图片上进行悬停,图片不会自动更新
  • 使用鼠标在小点上进行滑动,图片更新到对应的图片上

实现思路

获取DOM元素

首先需要获取页面中的各个DOM元素,包括图片、小圆点、箭头等:

// 小圆点的父类
let dotul = document.querySelector('.dot ul')
// 图片
let one = document.querySelector('.one')
let three = document.querySelector('.three')
// 我们图片的大框架
let carousel_map = document.querySelector('.carousel-map')
// 左边箭头
let lefticon = document.querySelector('.lefticon')
// 右边箭头
let righticon = document.querySelector('.righticon')
// 图片的父ul
let ul = document.querySelector('.ul-img')
// 左边图片的位置
let leftbox = document.querySelector('.leftbox')
// 右边图片的位置
let rightbox = document.querySelector('.rightbox')

小圆点实现

动态添加图片下的小圆点,使用for循环使用createElement()创建li元素,然后将创建的li添加到ul当中,但是因为我们显示的有图片和圆点进行绑定,所以我们要给一个小圆点添加上一个不一样的样式,添加了一个自定义样式,突出该圆点和图片的关联性,最开始我们要初始化一个小圆点,保证它可以和我们的第一个显示的图片相照应,这里我们首先显示的是第二个图片,所以在这里我们定义一个变量j为1,就是让我们的第二个小圆点进行显示,color()方法是给我们的小圆点上色的方法:

//添加小点点
for (let i = 0; i < parts.length; i++) {
  let li = document.createElement('li')
  // 添加自定义属性
  li.setAttribute('index', i)
  dotul.appendChild(li)
}
let j = 1
dotul.children[j].className = 'change'
function color() {
  for (let i = 0; i < parts.length; i++) {
    dotul.children[i].className = ''
  }
  dotul.children[j].className = 'change'
}

轮播图移动方法

定义parts数组,为的是让我们的图片类名进行更换:

let parts = ['one', 'two', 'three', 'four', 'five', 'six']

通过CSS对不同类名的图片进行位置和大小的设置:

.one {
  transform: translateX(-100px) scale(0.9);
  /* 初始位置和大小 */
  transition: transform 0.6s ease-out;
  /* 设置平滑过渡 */
  z-index: 4;
}
.two {
  transform: scale(1);
  /* 初始位置和大小 */
  transition: transform 0.6s ease;
  /* 设置平滑过渡 */
  z-index: 6;
}
.three {
  transform: translateX(100px) scale(0.9);
  /* 初始位置和大小 */
  transition: transform 0.5s ease-out;
  /* 设置平滑过渡 */
  z-index: 3;
}
.four {
  opacity: 0;
  transform: scale(0.9);
  z-index: 1;
}
.five {
  opacity: 0;
  transform: scale(0.9);
  z-index: 1;
}
.six {
  opacity: 0;
  transform: scale(0.9);
  z-index: 1;
}

实现向左和向右更新的方法:

function right() {
  // 将最后一个元素推到数组的前面
  parts.unshift(parts[5]) // 移动最后一个到最前面
  parts.pop()
  for (let i = 0; i < parts.length; i++) {
    if (ul.children[i]) {
      // 确保子元素存在
      ul.children[i].setAttribute('class', parts[i])
    }
  }
  j++
  inspect()
  color()
}
function left() {
  // 将最后一个元素推到数组的前面
  parts.push(parts[0]) // 移动最后一个到最前面
  parts.shift()
  for (let i = 0; i < parts.length; i++) {
    if (ul.children[i]) {
      // 确保子元素存在
      ul.children[i].setAttribute('class', parts[i])
    }
  }
  j--
  inspect()
  color()
}

鼠标悬停小圆点

实现小圆点与图片的联动:

dotul.addEventListener('mouseover', function (e) {
  if (e.target.tagName === 'LI') {
    let index = parseInt(e.target.getAttribute('index'))
    let now = parts.indexOf('two') // 获取当前显示的元素索引
    let dif = Math.abs(index - now) // 计算经过点与当前点的距离
    clearInterval(timer) // 清除定时器
    // 使用一个新的定时器来逐步移动
    if (index < now) {
      while (dif--) {
        left()
      }
    } else {
      while (dif--) {
        right()
      }
    }
    timer = setInterval(right, 1500) // 重新设置自动播放定时器
  }
})

图片停止自动播放

当鼠标悬停到轮播图上时,停止自动播放:

carousel_map.addEventListener('mouseover', function () {
  lefticon.style.display = 'block'
  righticon.style.display = 'block'
  clearInterval(timer)
})
carousel_map.addEventListener('mouseout', function () {
  lefticon.style.display = 'none'
  righticon.style.display = 'none'
  clearInterval(timer)
  timer = setInterval(right, 1500)
})

图片图标的点击事件

实现点击事件:

lefticon.addEventListener('click', function () {
  clearInterval(timer)
  left()
  timer = setInterval(right, 1500)
})
righticon.addEventListener('click', function () {
  clearInterval(timer)
  right()
  timer = setInterval(right, 1500)
})
leftbox.addEventListener('click', function () {
  clearInterval(timer)
  left()
  timer = setInterval(right, 1500)
})
rightbox.addEventListener('click', function () {
  clearInterval(timer)
  right()
  timer = setInterval(right, 1500)
})

完整代码

以下是完整的HTML代码,包含了CSS样式和JavaScript逻辑:

<!DOCTYPE html>
<html lang="chn">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      /* 一些简单的初始化文件 */
      * {
        margin: 0;
        padding: 0;
      }
      a {
        text-decoration: none;
      }
      li {
        list-style-type: none;
      }
      /* 更改图片的大小 */
      img {
        width: 100%;
        border-radius: 20px;
        box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.2);
      }
      /* 确定盒子的大小 */
      .box {
        position: relative;
        width: 958px;
        height: 284px;
        /* 居中 */
        top: 0;
        left: 50%;
        transform: translate(-50%, 50%);
      }
      .imgs {
        position: absolute;
        width: 730px;
        height: 284px;
        top: 0;
        left: 50%;
        transform: translate(-50%, 0%);
      }
      /* 让图片都叠在一起 */
      .imgs li {
        position: absolute;
        width: 730px;
        transition: 0.5s;
      }
      /* 给左右按钮设计样式,和定位 */
      .box .left {
        position: absolute;
        font-size: 24px;
        color: white;
        width: 36px;
        height: 36px;
        line-height: 36px;
        text-align: center;
        background-color: black;
        border-radius: 18px;
        /* 添加半透明 */
        opacity: 0.3;
        top: 50%;
        left: 0;
        z-index: 999;
      }
      .box .right {
        position: absolute;
        font-size: 24px;
        color: white;
        width: 36px;
        height: 36px;
        line-height: 36px;
        text-align: center;
        background-color: black;
        border-radius: 18px;
        /* 添加半透明 */
        opacity: 0.3;
        top: 50%;
        right: 0;
        z-index: 999;
      }
      /* 给左右按钮添加鼠标移入样式 */
      .left:hover {
        /* 把透明度挑高一点,让按钮看起来更亮一些 */
        opacity: 0.7;
      }
      .right:hover {
        opacity: 0.7;
      }
      img {
        width: 600px;
        height: 240px;
        background-repeat: no-repeat;
        background-size: contain;
      }
      /* 把图片错开 */
      .imgs .one {
        transform: translateX(-150px) scale(0.9);
        z-index: 1;
      }
      /* 第二张图片在中间,层级最高 */
      .imgs .two {
        z-index: 2;
      }
      .imgs .three {
        transform: translateX(150px) scale(0.9);
        z-index: 1;
      }
      /* 刚开始不显示的图片就放在中间图片的下面 */
      .imgs .four {
        transform: scale(0.9);
      }
      .imgs .five {
        transform: scale(0.9);
      }
      .imgs .six {
        transform: scale(0.9);
      }
      /* 设计小圆圈 */
      /* 定位 */
      .list {
        position: absolute;
        bottom: -25px;
        left: 50%;
        margin-left: -81px;
        z-index: 777;
      }
      /* 设计样式 */
      .list li {
        float: left;
        width: 15px;
        height: 15px;
        background-color: rgb(230, 230, 230);
        border-radius: 50%;
        margin: 0 6px;
        cursor: pointer;
      }
      /* 小圆圈改变后的样式 */
      .list .change {
        background-color: rgb(236, 65, 65);
      }
      /* 左右两边各一个盒子 */
      .rights {
        position: absolute;
        right: 0;
        bottom: 30px;
        height: 255.5px;
        width: 100px;
      }
      .lefts {
        position: absolute;
        left: 0;
        bottom: 14px;
        height: 255.5px;
        width: 100px;
      }
    </style>
  </head>
  <body>
    <!-- 大盒子 -->
    <div class="box">
      <!-- 左侧按钮 -->
      <a href="javascript:;" class="left">&lt</a>
      <!-- 右侧按钮 -->
      <a href="javascript:;" class="right">&gt</a>
      <!-- 轮播图片 -->
      <ul class="imgs">
        <li class="one">
          <a href="#"><img src="../image/carousel/carousel1.png" alt="1" /></a>
        </li>
        <li class="two">
          <a href="#"><img src="../image/carousel/carousel2.png" alt="2" /></a>
        </li>
        <li class="three">
          <a href="#"><img src="../image/carousel/carousel3.png" alt="3" /></a>
        </li>
        <li class="four">
          <a href="#"><img src="../image/carousel/carousel4.png" alt="4" /></a>
        </li>
        <li class="five">
          <a href="#"><img src="../image/carousel/carousel5.png" alt="5" /></a>
        </li>
        <li class="six">
          <a href="#"><img src="../image/carousel/carousel6.png" alt="6" /></a>
        </li>
      </ul>
      <!-- 小圆圈 -->
      <ul class="list"></ul>
      <!-- 两个空盒子,实现左右两侧图片点击效果 -->
      <div class="rights"></div>
      <div class="lefts"></div>
    </div>
    <script>
      window.addEventListener('load', function () {
        //获取元素
        var leftb = document.querySelector('.left')
        var rightb = document.querySelector('.right')
        var box = document.querySelector('.box')
        var imgs = box.querySelector('.imgs')
        var imgt = imgs.querySelectorAll('li')
        //自动翻页函数
        var timeone = setInterval(function () {
          rightf()
        }, 1000)
        //左右按钮的出现
        box.addEventListener('mouseover', function () {
          leftb.style.display = 'block'
          rightb.style.display = 'block'
          //移入时清除定时器
          clearInterval(timeone)
          timeone = null
        })
        //左右按钮的消失
        box.addEventListener('mouseout', function () {
          leftb.style.display = 'none'
          rightb.style.display = 'none'
          //恢复定时器
          clearInterval(timeone)
          timeone = setInterval(function () {
            rightf()
          }, 1500)
        })
        //动态生成小圆圈,小圈圈模块
        var list = box.querySelector('.list')
        for (var i = 0; i < imgs.children.length; i++) {
          //创建li,加入ul中
          var li = document.createElement('li')
          list.appendChild(li)
          //给小圈圈添加类名
          li.setAttribute('index', i)
          //排他思想,实现点击小圆圈,变色
          // li.addEventListener('click', colors);
          //经过小圆圈,切换图片
          li.addEventListener('mouseenter', jump)
        }
        //一开始第二个亮
        list.children[1].className = 'change'
        //变色函数
        function colors() {
          //把所有的小圆圈变白
          for (var i = 0; i < list.children.length; i++) {
            list.children[i].className = ''
          }
          //给图片对应的小圆圈上色
          var index = this.getAttribute('index')
          list.children[index].className = 'change'
        }
        //跳转函数
        function jump() {
          var index = this.getAttribute('index')
          var now = num.indexOf('two')
          //计算经过点与当前点的距离
          var dif = Math.max(index, now) - Math.min(index, now)
          // console.log(dis);
          if (index > now) {
            while (dif--) {
              rightf()
            }
          } else {
            while (dif--) {
              leftf()
            }
          }
        }
        //小圆圈跟随着图片移动
        var j = 1
        function colort() {
          for (var i = 0; i < list.children.length; i++) {
            list.children[i].className = ''
          }
          if (j >= 6) {
            j = 0
          } else if (j < 0) {
            j = 5
          }
          list.children[j].className = 'change'
        }
        //翻页模块
        var num = ['one', 'two', 'three', 'four', 'five', 'six']
        //右翻页
        rightb.addEventListener('click', rightf)
        function rightf() {
          //把数组的最后一个添加到第一个
          num.unshift(num[5])
          //删除最后一个
          num.pop()
          //重新给li添加类名
          for (var i = 0; i < num.length; i++) {
            imgt[i].setAttribute('class', num[i])
          }
          //通过这个全局变量来让小圆圈的颜色一起变化
          j++
          colort()
        }
        //左翻页
        leftb.addEventListener('click', leftf)
        function leftf() {
          num.push(num[0])
          num.shift()
          for (var i = 0; i < num.length; i++) {
            imgt[i].setAttribute('class', num[i])
          }
          j--
          colort()
        }
        //点击图片实现翻页,这里我是通过在左右两边添加一个盒子来实现的
        var rights = document.querySelector('.rights')
        rights.addEventListener('click', function () {
          rightf()
        })
        var lefts = document.querySelector('.lefts')
        lefts.addEventListener('click', function () {
          leftf()
        })
      })
    </script>
  </body>
</html>

以上代码实现了一个功能丰富的轮播图效果,包括图片的左右切换、小圆点导航、鼠标悬停停止等功能。读者可以根据需要调整图片路径和样式,以适应不同的项目需求。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号