首页 > 解决方案 > 使用javascript在图像之间切换

问题描述

所以我在 js 中有一个小脚本,它会随着时间的推移改变图像,我想添加两个按钮,如果有人不想等待,可以跳过图像,但它们并没有真正起作用,点击它们只会让我回来到第一张图片。

这是我发现的随时间更改图像的脚本:

<script>
var imageSources = ["image1.png", "image2.png","image3.png"];
var index = 0;
setInterval (function(){
  if (index === imageSources.length) {
    index = 0;
  }
  document.getElementById("image").src = imageSources[index];
  index++;
} , 2000);

这是我试图在点击时更改它们的脚本:

 function changeImage1() {
        if (document.getElementById("image").src == "image1.png") 
        {
        document.getElementById("image").src = "image3.png";    
        }
        else if (document.getElementById("image").src == "image2.png")
        {
            document.getElementById("image").src = "image1.png";
        }
        else if (document.getElementById("image").src == "image3.png")
        {
            document.getElementById("image").src = "image2.png";
    }
    else {}
 }
function changeImage2() {
        if (document.getElementById("image").src == "image1.png") 
        {
            document.getElementById("image").src = "image2.png";
        }
        else if (document.getElementById("image").src == "image2.png")
        {
            document.getElementById("image").src = "image3.png";
        }
        else if (document.getElementById("image").src == "image3.png"){
            document.getElementById("image").src = "image1.png";
        }
        else {}
    }
</script>

和html:

<button name="button1" id="button1" onclick="changeImage1()">
<img src="arrow_left.png" width="50px" height="50px"/>
</button>
<img name="image" id="image" src="image1.png" width="800px" height="300px"/>
<button name="button2" id="button2" onclick="changeImage2()">
<img src="arrow_right.png" onclick="changeImage2()" width="50px" height="50px"/>
</button>

标签: javascripthtmlonclick

解决方案


您正在寻找类似于滑块的功能。您展示的第一个片段setInterval是一个很好的工作场所。遍历列表使您的代码动态化,并允许添加或删除项目而无需更改太多代码。

我已经扩展了您提供的代码,并在下面制作了一个可行的片段。请务必检查一下。

而不是setInterval我用过的setTimeout. 这是因为按钮和循环都使用相同的功能来显示当前图像。所以循环将能够再次调用自己。并且当循环在 2 秒过去之前被调用时,它将被取消并重新开始。当您单击其中一个按钮时,可能会发生这种情况。

我删除了内联onclick侦听器以支持addEventListener在 JavaScript 中使用。我建议你采用这种方法。它将允许您重复更少的代码,将您的 JavaScript 保存在一个地方,并使您的代码更加灵活。
但是,我确实value为按钮添加了一个属性。按钮支持此属性。它可以携带少量信息,例如告诉您此按钮是上一个按钮还是下一个按钮。value可以使用对象的属性轻松读取该属性valueHTMLButtonElement这是 JS 等价的 a <button>)。

如果您有任何问题,请务必提出,因为我认为有些事情对您来说可能是新的。

// The element to display the image with.
const imageElement = document.querySelector('.js-image-display');

// The buttons to go previous and next.
const imageButtons = document.querySelectorAll('.js-image-control');

// Available sources of images.
const imageSources = [
  "https://www.placecage.com/c/800/300", 
  "https://www.placecage.com/800/300",
  "https://www.fillmurray.com/800/300",
  "https://www.placecage.com/g/800/300",
  "https://www.fillmurray.com/g/800/300"
];

// Current displayed image.
let currentImageIndex = 0;

// Variable to store the loop in.
let currentLoop;

// Show first image and start looping.
showCurrentImage();

/**
 * Cancel previous loop, wait for 2 seconds and call nextImage().
 * nextImage() will then call showCurrentImage which will call
 * loop() again. This will keep the cycle going.
 */
function loop() {
  clearTimeout(currentLoop);
  currentLoop = setTimeout(nextImage, 2000);
}

/**
 * Update the src of the imageElement with the 
 * current image index. Then reset the loop.
 */
function showCurrentImage() {
  imageElement.src = imageSources[currentImageIndex];
  loop();
}

/**
 * Remove 1 from the current image index
 * or go back to the end. Then show the image.
 */
function prevImage() {
  if (currentImageIndex === 0) {
    currentImageIndex = imageSources.length - 1;
  } else {
    currentImageIndex--;
  }
  showCurrentImage();
}

/**
 * Add 1 to current image index or go 
 * back to the start. Then show the image.
 */
function nextImage() {
  if (currentImageIndex === imageSources.length - 1) {
    currentImageIndex = 0;
  } else {
    currentImageIndex++;
  }
  showCurrentImage();
}

// Link the prev and next words to their corresponding functions.
// This way you don't have to write a lot of if / else statements
// to get the function based on the value of the button.
const actionMap = {
  'prev': prevImage,
  'next': nextImage
}

/**
 * Decide by reading the value attribute if nextImage or
 * prevImage should be called. event.currentTarget is one
 * of the two buttons that you've clicked. It gets the value
 * and looks up the function to call from the actionMap.
 *
 * @param {Event} event Click event triggerd by the buttons.
 */
function onButtonClick(event) {
  const value = event.currentTarget.value;
  const action = actionMap[value];
  action();
}

// Loop over the buttons and add an click event listener
// for each button in the list. In some older browser imageButtons
// might not be able to use forEach, so Array.from() turns it
// into an array so we know for sure that forEach is possible.
Array.from(imageButtons).forEach(function(button) {
  button.addEventListener('click', onButtonClick);
});
img {
  max-width: 100%;
  height: auto;
}
<!-- Prev button -->
<button class="js-image-control" value="prev">Previous</button>

<!-- Image -->
<img class="js-image-display" src="image1.png" width="800" height="300"/>

<!-- Next button -->
<button class="js-image-control" value="next">Next</button>


推荐阅读