首页 > 解决方案 > 轮播 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>

标签: javascripthtmlcssdom-events

解决方案


你在间隔上犯了一个错误。为了能够清除 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);
}

推荐阅读