【问题标题】:Identify window.scroll event when it triggered by user OR by an code executed by an event当 window.scroll 事件由用户触发或由事件执行的代码触发时识别它
【发布时间】:2019-07-22 09:49:53
【问题描述】:

我们是否有办法识别window.scroll 事件是由用户鼠标触发还是通过调用某个事件的函数来触发。 我正在使用 ES6,Typescript 和 angular。

我确实看到过去曾提出过与 jQuery 相关的问题,并且粘贴在下面的建议解决方案现在不再起作用。无论如何触发滚动,e.originalEvent 始终存在。

$('#scroller').scroll(function(e) {
    if (e.originalEvent) {
        console.log('scroll happen manual scroll');
    } else {
        console.log('scroll happen by call');
    }
});

【问题讨论】:

  • 是您以编程方式触发滚动事件的函数。如果是,那怎么办?通过使用 jquery animate 或其他什么。
  • @localhost 是的,功能是我的。当用户单击链接时,我会触发该功能并滚动到与该链接相关的特定部分。我为此使用“windows.location.hash”。不使用 jQuery。

标签: javascript angular typescript ecmascript-6


【解决方案1】:

您可以使用鼠标滚轮事件onwheel,来检测滚动是否由鼠标启动。

但是,这仅限于用户滚动鼠标滚轮同时将光标置于相关容器内的情况,不会解决用户抓住并移动滚动条或滚动条时的问题。由向上或向下按键触发

更好的方法可能是反转在下面的 sn-p 中处理 isWheel 标志的逻辑,并使用由那些以编程方式触发的处理程序设置/取消设置的isNotWheel 标志,并将滚动容器内容。

请注意,timerSet/ClearTimeout 在示例中被用于充分支持 Frefox,它只在鼠标滚动开始时发出一次滚轮事件,而 Chrome 则同时发出滚轮事件和滚动事件在滚动运动的整个过程中。

$(() => {

  const main = document.getElementsByTagName('article')[0];
  const a = document.getElementsByTagName('a')[0];
  let isWheel = false;
  let timer = null;
  
  $(main).scroll( e => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      isWheel = false;
    }, 100);
    
    if (isWheel) {
      console.log('Scroll triggered by mouse wheel');
    } else {
      console.log('Scroll NOT triggered by mouse wheel');
    } 
  });
  main.addEventListener('wheel', e => {
    isWheel = true;
  });
  
  $(a).click( e => {
    main.scrollTo(0, 0);
  });
  
})
.main {
  height: 150px;
  overflow-y: scroll;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article class="main">
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
<div>
 scroll me
</div>
</article>
<a href="javascript:void(0);">Trigger scroll by "function"</a>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 2013-04-02
    相关资源
    最近更新 更多