实现轮播图的大致思路如下:

  1. 获取轮播图容器元素和图片列表元素;
  2. 设置图片列表元素的宽度和高度,使其能够水平排列;
  3. 设置定时器,每隔一定时间切换当前显示的图片;
  4. 设置前进和后退按钮,点击按钮时切换当前显示的图片。

下面是一个简单的实现示例:

HTML 代码:

<div class='carousel'>
  <ul class='images'>
    <li><img src='image1.jpg'></li>
    <li><img src='image2.jpg'></li>
    <li><img src='image3.jpg'></li>
  </ul>
  <button class='prev'>Prev</button>
  <button class='next'>Next</button>
</div>

CSS 代码:

.carousel {
  position: relative;
  width: 500px;
  height: 300px;
  overflow: hidden;
}
.carousel .images {
  position: absolute;
  left: 0;
  top: 0;
  width: 1500px;
  height: 300px;
  margin: 0;
  padding: 0;
}
.carousel .images li {
  float: left;
  list-style: none;
  margin: 0;
  padding: 0;
}
.carousel .images img {
  width: 500px;
  height: 300px;
}
.carousel .prev,
.carousel .next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  border: none;
  outline: none;
  cursor: pointer;
}
.carousel .prev {
  left: 10px;
}
.carousel .next {
  right: 10px;
}

JavaScript 代码:

var carousel = document.querySelector('.carousel');
var images = document.querySelector('.images');
var prevBtn = document.querySelector('.prev');
var nextBtn = document.querySelector('.next');
var currentIndex = 0;
var timer;

// 设置图片列表元素的宽度和高度
images.style.width = images.children.length * 500 + 'px';

// 切换到指定索引的图片
function goToIndex(index) {
  // 判断索引是否越界
  if (index < 0) {
    index = images.children.length - 1;
  } else if (index >= images.children.length) {
    index = 0;
  }
  // 设置当前显示的图片和按钮样式
  images.style.left = -index * 500 + 'px';
  currentIndex = index;
}

// 切换到下一张图片
function next() {
  goToIndex(currentIndex + 1);
}

// 切换到上一张图片
function prev() {
  goToIndex(currentIndex - 1);
}

// 启动定时器
function start() {
  timer = setInterval(next, 3000);
}

// 停止定时器
function stop() {
  clearInterval(timer);
}

// 绑定事件
prevBtn.addEventListener('click', function() {
  stop();
  prev();
  start();
});
nextBtn.addEventListener('click', function() {
  stop();
  next();
  start();
});

// 启动轮播图
start();

以上代码实现了一个简单的轮播图,可以用作参考。当然,实际应用中还需要考虑更多的细节问题,如图片的预加载、自适应宽度、响应式布局等。

JavaScript 轮播图实现:完整指南及示例代码

原文地址: https://www.cveoy.top/t/topic/mxVL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录