【问题标题】:onmouseover and onmouseout setIntervalonmouseover 和 onmouseout 设置间隔
【发布时间】:2020-12-10 10:58:35
【问题描述】:

我一直被这个问题困扰。我正在为我的应用程序使用滑块。为了滑动我正在使用的应用程序splide-js。我的图像滑块工作正常。

我已将我的滑块与我的li 元素连接起来。我想定制onmouseoveronmouseout 事件。当用户在li 上触发mouseover 时,它会暂停,当mouseout 时,它会继续滑动。

我正在检查这个 Stack Overflow post 并尝试使用 setinterval 来像这个人一样做逻辑,但无法做到这一点。

const autoPlay = false;
const pauseOnHover = document.getElementById('pause');

function nextSlide() { //I don't what kind logic I should use to pause the slide

}

let  timer = setInterval(function() {
  nextSlide();
}, 400);


pauseOnHover.onmouseover = () => {
  if( autoPlay) {
    timer
  }
}
pauseOnHover.onmouseout = () => {
  if (autoPlay) {
    clearInterval(timer)
  }
}
<div class='checklist' id="pause">
  <ol>
    <li id="link-1">Assign jobs in an instant.</li>
    <li id="link-2">Always see what's happening.</li>
    <li id="link-3">Easy to set-up & use.</li>
    <li id="link-4">Be more sustainable</li>
  </ol>
</div>

【问题讨论】:

  • 您是否尝试过使用autoplay : true, pauseOnHover:false 属性?

标签: javascript html onmouseover onmouseout


【解决方案1】:

请在鼠标悬停时初始化并重新初始化间隔,如果存在间隔则在鼠标退出时取消。

请尝试以下代码。

const autoPlay = false;
const pauseOnHover = document.getElementById('pause');

function nextSlide() {
  //For example I have put console.log, you mat put any code block here.
  console.log("hello");
}

let timer;


pauseOnHover.onmouseover = () => {

  autoplay = true;
  if (!autoPlay) {
    autoplay = true;
    timer = setInterval(function() {
      nextSlide();
    }, 400);
  }
}
pauseOnHover.onmouseout = () => {

  autoplay = false;
  timer && clearInterval(timer)

}
<div class='checklist' id="pause">
  <ol>
    <li id="link-1">Assign jobs in an instant.</li>
    <li id="link-2">Always see what's happening.</li>
    <li id="link-3">Easy to set-up & use.</li>
    <li id="link-4">Be more sustainable</li>
  </ol>
</div>

【讨论】:

  • splide 上有一个pauseOnHover 选项/属性。在创建 splide 时,如果 OP 实现了该属性,那么 OP 可以轻松实现他想要的;)不需要额外的代码
  • 我的答案是以 JS 方式修复'onmouseover 和 onmouseout setInterval'。是的,如果有 API 可以解决问题,那就太好了。
  • 是的,我看到了 pauseOnHover 选项,但我不知道如何在我的 ul 元素中使用它们。这是我的滑动逻辑。 const splide = new Splide('.mobile-splide', { type: 'loop', autoplay: true, interval: 3000, perPage: 1 }).mount();
  • 是的,我同意@Sivakumar
猜你喜欢
  • 2023-03-03
  • 1970-01-01
  • 2012-02-04
  • 2015-08-27
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 2011-06-27
  • 1970-01-01
相关资源
最近更新 更多