【问题标题】:Carousel onmouseover and onmouseout does not work轮播 onmouseover 和 onmouseout 不起作用
【发布时间】:2020-09-12 07:07:51
【问题描述】:

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

【问题讨论】:

    标签: javascript html css dom-events


    【解决方案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);
    }
    

    【讨论】:

    • 非常感谢@Nikko。正如我提到的,我是初学者:)。我有几个问题要问你:1.why you assign to variable? 2.why in clearinterval you added + 1, 3.since x = setInterval(run, 2000); then why not just put x in onmouseout
    • 不客气@krisna。回答你的问题。 1. 您需要将其分配给一个变量,因为稍后您将在 clearInterval 中使用它。 2.实际上,您省略了“+ 1”,我只是从您的代码中复制了它。 3. 因为clearInterval清空了定时器,所以需要重新设置。
    猜你喜欢
    • 2013-02-16
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2012-02-04
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    相关资源
    最近更新 更多