亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 javascript 在圖像之間切換

使用 javascript 在圖像之間切換

慕哥6287543 2023-10-20 15:01:19
所以我在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>
查看完整描述

3 回答

?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

所以我想你想要一個按鈕來跳過圖像和一個按鈕來顯示上一張圖像。

首先我們聲明變量


const img = document.getElementById("image"); // the img element 

const imageSources = ["image1.png", "image2.png","image3.png"];

let index = 0;

let travel; // here the most important thing 

您必須創建一個啟動函數,以便您可以在頁面加載或重置計時器時調用它


const startTravel = () => {

    travel = setInterval(() => {

      ++index;

      if (index < 0 || index === imageSources.length) index = 0;

      img.src = imageSources[index];

    }, 2000);

};

下一個圖像函數就像


const changeImage2 = () => {

  clearInterval(travel);

  img.src = imageSources[++index];

  startTravel();

}

之前的圖像函數就像


const changeImage1 = () => {

  clearInterval(travel);

  img.src = imageSources[--index];

  startTravel();

}

它還沒有完成,當你點擊跳過 5 次時,它會將索引設置為 6,而 6 不在 imageSources 中,所以我不想為你做這件事,因為它很容易,我認為你必須做到這一點


完整代碼


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>


<button id="button1" onclick="changeImage1()">

    left

</button>


<img src="image1.jpg" alt="img" id="img">


<button id="button2" onclick="changeImage2()">

    right

</button>


<script>

  const img = document.getElementById("img");

  const imageSources = ["image1.jpg", "image2.jpg", "image3.jpg"];

  let index = 0;

  let travel;


  const startTravel = () => {

    travel = setInterval(() => {

      ++index;


      console.log(index);

      if (index < 0 || index === imageSources.length) index = 0;

      img.src = imageSources[index];

    }, 6000);

  };


  const changeImage1 = () => {

    if (index === 0) index = imageSources.length;


    clearInterval(travel);

    img.src = imageSources[--index];

    startTravel();

  }


  const changeImage2 = () => {

    if (index === imageSources.length - 1) index = -1;


    clearInterval(travel);

    img.src = imageSources[++index];

    startTravel();

  }


  startTravel();

</script>

</body>

</html>


查看完整回答
反對 回復 2023-10-20
?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

您正在尋找類似于滑塊的功能。您顯示的第一個片段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 = [

  "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>


查看完整回答
反對 回復 2023-10-20
?
江戶川亂折騰

TA貢獻1851條經驗 獲得超5個贊

事情是,


  if (index === imageSources.length) {

    index = 0;

  }

這行代碼或三行代碼等待 imageSources 長度變為 3,但 imageSources 從 1 開始計數,因此如果 imageSources 變量包含 3 個元素,則長度將為 3。然而索引是由 0 完成的,所以你必須將代碼更改為


  if (index === (imageSources.length - 1)) {

    index = 0;

  }


查看完整回答
反對 回復 2023-10-20
  • 3 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號