javascript - 轮播 onmouseover 和 onmouseout 不起作用
问题描述
我正在练习 Javascript。我做了一个图像轮播。我的旋转木马幻灯片工作正常。要运行我使用的幻灯片setinterval
。当用户将鼠标悬停在图像上时,我想停止幻灯片,当它悬停时,幻灯片将从暂停的地方开始。为此,我使用了clearinterval
. 当我onmouseover
然后onmouseout
我的旋转木马表现得很奇怪。似乎我的逻辑不起作用。我不知道该怎么做。
const images = document.getElementById('imgs')
const allImages = document.querySelectorAll('#imgs img')
let index = 0;
function run() {
index++;
if (index > allImages.length - 1) {
index = 0
}
imgs.style.transform = `translateX(${-index * 500}px)`
}
setInterval(run, 2000);
images.onmouseover = () => {
console.log('In');
clearInterval(run) + 1
}
images.onmouseout = () => {
console.log('Out');
setInterval(run, 2000);
}
*{
box-sizing: border-box;
}
body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.carousel {
overflow: hidden;
width: 500px;
height: 500px;
box-shadow: 2px 2px 5px rgba(0, 0, 0, .3);
}
.image-container {
display: flex;
transition: transform 300ms linear;
transform: translateX(0);
}
img {
width:500px;
height: 500px;
object-fit: cover;
}
<div class="carousel">
<div class="image-container" id="imgs" >
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
<img src="https://images.unsplash.com/photo-1516026672322-bc52d61a55d5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
<img src="https://images.unsplash.com/photo-1573081586928-127ecc7948b0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
<img src="https://images.unsplash.com/flagged/photo-1572850005109-f4ac7529bf9f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
</div>
解决方案
你在间隔上犯了一个错误。为了能够清除 onmouseover 事件中的时间间隔,您需要将其分配给一个变量
var x = setInterval(run, 2000);
然后将变量传递给clearInterval方法。
clearInterval(x)
然后 onmouseout 你再次设置间隔
x = setInterval(run, 2000);
最终代码如下所示:
var x = setInterval(run, 2000);
images.onmouseover = () => {
console.log('In');
clearInterval(x) + 1
}
images.onmouseout = () => {
console.log('Out');
x = setInterval(run, 2000);
}
推荐阅读
- python - 使用 Tshark 在较小的部分中读取大型 PCAP
- python - Python中的非二叉树数据结构
- angular - 在导航侧边栏中,Angular Material CDK Overlay 滚动块不起作用
- flutter - Flutter:ListView:当子 ListView 到达底部时滚动父 ListView - ClampingScrollPhysics 在大小容器中不起作用
- mysql - 在 IN() 条件中混合引用和未引用的值 - MySQL 怪癖或一般问题?
- typescript - 如何在给定枚举值的情况下指定同级字段类型?
- python - 填充和注意掩码在 GPT 语言模型的批量输入中无法按预期工作
- java - Modern Java in Action 中有关 java 流 dropWhile 示例的问题
- android - 命令:`react-native run-android` 挂在“信息正在启动 JS 服务器...”
- python - 如何使用 python 子进程执行命令并响应多个输入?