轮播onmouseover和onmouseout不起作用

时间:2020-09-12 07:07:51

标签: javascript html css dom-events

我正在练习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>

1 个答案:

答案 0 :(得分:1)

您错了间隔。 为了能够清除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);
}