![](/img/trans.png)
[英]How to make reverse scrolling identical as one going to “right” direction on my “Frankensteinian” bootstrap carousel?
[英]How do I reverse the direction of my javascript image carousel?
我有一個圖像輪播,默認情況下向右旋轉。 使用 setInterval() 並每隔幾秒更改一次圖像。 我創建了兩個 setInterval 函數,一個向右旋轉,一個向左旋轉。
然后我創建了一個 html 箭頭並添加了一個 onclick 調用以調用我想要的特定 setInterval。 問題是以前的 setIntervals 在調用新的 setIntervals 時不會關閉。 我嘗試使用 clearInterval,但沒有用。
我的代碼看起來像:
const left_arrow = document.querySelector("#arrow");
var rotateRight = setInterval(()=>{
// do stuff
}, 3000)
var rotateLeft = setInterval(()=>{
// do stuff
}, 3000)
left_arrow.onclick = rotateLeft();
right_arrow.onclick = rotateRight();
我基本上希望能夠單擊箭頭並通過調用不同的 setInterval 函數讓它旋轉我的圖像流。 我不能使用任何框架。 謝謝你。
SetInterval 僅每 x 毫秒執行一次操作,因此對於您的代碼,您每三秒向左然后向右移動。 這是我認為可行的代碼
direction = "right"
setInterval(()=>{
if(direction === "right") {
//do stuff to rotate right
} else {
//do stuff to rotate left
}
}, 3000)
left_arrow.onclick = () => {
direction = "left";
};
right_arrow.onclick = () => {
direction = "right";
};
因此,解釋代碼在做什么,變量 direction 存儲輪播應該移動的方向,setInterval 中的代碼每 3 秒運行一次,如果方向正確,則運行一些代碼,否則運行其他代碼。 當您單擊按鈕時,它只是設置方向。
我認為 clearInterval 會在您的場景中起作用,可能是您在錯誤的時間使用了 clearInterval。 如果您不確定,請粘貼更多代碼。
其次, const left_arrow = document.querySelector("#arrow");
#arrow 元素被命名為 left_arrow,我不知道你的 right_arrow 元素 id 是什么,可能這也是一個問題。
正如@Dominik 評論的那樣,停止原始間隔的解決方案是使用clearInterval
當你調用setInterval
時
const left_arrow = document.querySelector("#arrow");
let currentInterval = null;
function rotateRight(){
return setInterval(()=>{
clearInterval(currentInterval)
// do stuff
}, 3000)
}
function rotateLeft(){
return setInterval(()=>{
clearInterval(currentInterval)
// do stuff
}, 3000)
}
left_arrow.onclick = ()=> {currentInterval = rotateLeft();}
right_arrow.onclick = ()=> {currentInterval = rotateRight();}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.