使用 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>


慕哥6287543
浏览 116回答 3
3回答

互换的青春

所以我想你想要一个按钮来跳过图像和一个按钮来显示上一张图像。首先我们声明变量const img = document.getElementById("image"); // the img element&nbsp;const imageSources = ["image1.png", "image2.png","image3.png"];let index = 0;let travel; // here the most important thing&nbsp;您必须创建一个启动函数,以便您可以在页面加载或重置计时器时调用它const startTravel = () => {&nbsp; &nbsp; travel = setInterval(() => {&nbsp; &nbsp; &nbsp; ++index;&nbsp; &nbsp; &nbsp; if (index < 0 || index === imageSources.length) index = 0;&nbsp; &nbsp; &nbsp; img.src = imageSources[index];&nbsp; &nbsp; }, 2000);};下一个图像函数就像const changeImage2 = () => {&nbsp; clearInterval(travel);&nbsp; img.src = imageSources[++index];&nbsp; startTravel();}之前的图像函数就像const changeImage1 = () => {&nbsp; clearInterval(travel);&nbsp; img.src = imageSources[--index];&nbsp; startTravel();}它还没有完成,当你点击跳过 5 次时,它会将索引设置为 6,而 6 不在 imageSources 中,所以我不想为你做这件事,因为它很容易,我认为你必须做到这一点完整代码<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <title>Title</title></head><body><button id="button1" onclick="changeImage1()">&nbsp; &nbsp; left</button><img src="image1.jpg" alt="img" id="img"><button id="button2" onclick="changeImage2()">&nbsp; &nbsp; right</button><script>&nbsp; const img = document.getElementById("img");&nbsp; const imageSources = ["image1.jpg", "image2.jpg", "image3.jpg"];&nbsp; let index = 0;&nbsp; let travel;&nbsp; const startTravel = () => {&nbsp; &nbsp; travel = setInterval(() => {&nbsp; &nbsp; &nbsp; ++index;&nbsp; &nbsp; &nbsp; console.log(index);&nbsp; &nbsp; &nbsp; if (index < 0 || index === imageSources.length) index = 0;&nbsp; &nbsp; &nbsp; img.src = imageSources[index];&nbsp; &nbsp; }, 6000);&nbsp; };&nbsp; const changeImage1 = () => {&nbsp; &nbsp; if (index === 0) index = imageSources.length;&nbsp; &nbsp; clearInterval(travel);&nbsp; &nbsp; img.src = imageSources[--index];&nbsp; &nbsp; startTravel();&nbsp; }&nbsp; const changeImage2 = () => {&nbsp; &nbsp; if (index === imageSources.length - 1) index = -1;&nbsp; &nbsp; clearInterval(travel);&nbsp; &nbsp; img.src = imageSources[++index];&nbsp; &nbsp; startTravel();&nbsp; }&nbsp; startTravel();</script></body></html>

繁星点点滴滴

您正在寻找类似于滑块的功能。您显示的第一个片段setInterval是一个很好的工作场所。迭代列表使您的代码变得动态,并允许添加或删除项目,而无需更改太多代码。我扩展了您提供的代码,并在下面制作了一个可行的代码片段。一定要检查一下。而不是setInterval我用过的setTimeout. 这样做的原因是因为按钮和循环使用相同的功能来显示当前图像。所以循环将能够再次调用自身。当循环在 2 秒过去之前被调用时,它将被取消并重新开始。当您单击其中一个按钮时可能会发生这种情况。我已经删除了内联onclick侦听器,转而addEventListener在 JavaScript 中使用。我建议你采用这种方法。它将允许您重复更少的代码,将 JavaScript 保留在一个地方,并使您的代码更加灵活。不过,我确实value向按钮添加了一个属性。按钮支持此属性。它可以携带少量信息,例如告诉您此按钮是上一个按钮还是下一个按钮。该属性可以通过对象的属性(相当于 JS 中的 a )value轻松读取。valueHTMLButtonElement<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 = [&nbsp; "https://www.placecage.com/c/800/300",&nbsp;&nbsp; "https://www.placecage.com/800/300",&nbsp; "https://www.fillmurray.com/800/300",&nbsp; "https://www.placecage.com/g/800/300",&nbsp; "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();/**&nbsp;* Cancel previous loop, wait for 2 seconds and call nextImage().&nbsp;* nextImage() will then call showCurrentImage which will call&nbsp;* loop() again. This will keep the cycle going.&nbsp;*/function loop() {&nbsp; clearTimeout(currentLoop);&nbsp; currentLoop = setTimeout(nextImage, 2000);}/**&nbsp;* Update the src of the imageElement with the&nbsp;&nbsp;* current image index. Then reset the loop.&nbsp;*/function showCurrentImage() {&nbsp; imageElement.src = imageSources[currentImageIndex];&nbsp; loop();}/**&nbsp;* Remove 1 from the current image index&nbsp;* or go back to the end. Then show the image.&nbsp;*/function prevImage() {&nbsp; if (currentImageIndex === 0) {&nbsp; &nbsp; currentImageIndex = imageSources.length - 1;&nbsp; } else {&nbsp; &nbsp; currentImageIndex--;&nbsp; }&nbsp; showCurrentImage();}/**&nbsp;* Add 1 to current image index or go&nbsp;&nbsp;* back to the start. Then show the image.&nbsp;*/function nextImage() {&nbsp; if (currentImageIndex === imageSources.length - 1) {&nbsp; &nbsp; currentImageIndex = 0;&nbsp; } else {&nbsp; &nbsp; currentImageIndex++;&nbsp; }&nbsp; 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 = {&nbsp; 'prev': prevImage,&nbsp; 'next': nextImage}/**&nbsp;* Decide by reading the value attribute if nextImage or&nbsp;* prevImage should be called. event.currentTarget is one&nbsp;* of the two buttons that you've clicked. It gets the value&nbsp;* and looks up the function to call from the actionMap.&nbsp;*&nbsp;* @param {Event} event Click event triggerd by the buttons.&nbsp;*/function onButtonClick(event) {&nbsp; const value = event.currentTarget.value;&nbsp; const action = actionMap[value];&nbsp; 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) {&nbsp; button.addEventListener('click', onButtonClick);});img {&nbsp; max-width: 100%;&nbsp; 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>

江户川乱折腾

事情是,&nbsp; if (index === imageSources.length) {&nbsp; &nbsp; index = 0;&nbsp; }这行代码或三行代码等待 imageSources 长度变为 3,但 imageSources 从 1 开始计数,因此如果 imageSources 变量包含 3 个元素,则长度将为 3。然而索引是由 0 完成的,所以你必须将代码更改为&nbsp; if (index === (imageSources.length - 1)) {&nbsp; &nbsp; index = 0;&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript