以下是一个示例的JavaScript代码,可以实现在div两边添加箭头来切换图片:

// 获取div元素和图片列表
var div = document.getElementById('div_1');
var images = div.getElementsByTagName('img');

// 设置初始图片索引和箭头元素
var currentIndex = 0;
var arrowLeft = document.createElement('span');
var arrowRight = document.createElement('span');

// 添加箭头样式
arrowLeft.innerHTML = '←';
arrowLeft.style.position = 'absolute';
arrowLeft.style.left = '10px';
arrowLeft.style.top = '50%';
arrowLeft.style.transform = 'translateY(-50%)';
arrowLeft.style.cursor = 'pointer';
arrowRight.innerHTML = '→';
arrowRight.style.position = 'absolute';
arrowRight.style.right = '10px';
arrowRight.style.top = '50%';
arrowRight.style.transform = 'translateY(-50%)';
arrowRight.style.cursor = 'pointer';

// 添加箭头点击事件
arrowLeft.onclick = function() {
  currentIndex--;
  if (currentIndex < 0) {
    currentIndex = images.length - 1;
  }
  showImage(currentIndex);
};

arrowRight.onclick = function() {
  currentIndex++;
  if (currentIndex >= images.length) {
    currentIndex = 0;
  }
  showImage(currentIndex);
};

// 显示指定索引的图片
function showImage(index) {
  for (var i = 0; i < images.length; i++) {
    images[i].style.display = 'none';
  }
  images[index].style.display = 'block';
}

// 将箭头添加到div中
div.appendChild(arrowLeft);
div.appendChild(arrowRight);

// 显示初始图片
showImage(currentIndex);

请注意,上述代码假设div元素的id为div_1,并且图片元素是<img>标签。您需要根据实际情况进行调整,以确保代码能够正确运行

centerdiv id=div_1 style=width 800px;height 100;border 10px solid pink;img src=img1jpgimg src=imgzfmjpgimg src=img抽奖图片pngimg src=img鸭子图片jpgdivcenter帮我为这个写一个js使div两边有箭头用于切换图片

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

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