![](/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.