使“scrollLeft” /" scrollTop"更改不会触发滚动事件侦听器 [英] Make "scrollLeft" / "scrollTop" changes not trigger scroll event listener

查看:319
本文介绍了使“scrollLeft” /" scrollTop"更改不会触发滚动事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我的程序处于侦听用户滚动某个元素的位置,但有时也会自动滚动此元素。 (不是一个渐进的,漂亮的滚动,而是一个瞬间的跳跃,这是有道理的,我发誓。)

Currently my program is in a spot where it both listens for the user to scroll a certain element, but also, at times, automatically scrolls this element by itself. (Not a gradual, pretty scroll, but an instant jump. It makes sense in context, I swear.)

有没有办法让scroll事件不会触发if滚动是通过设置scrollLeft或scrollTop完成的?我的第一个想法是一个基本的开关,比如:

Is there a way to make the scroll event not trigger if the scrolling was done by setting scrollLeft or scrollTop? My first thought was a basic switch, like:

ignoreScrollEvents = true;
element.scrollLeft = x;
ignoreScrollEvents = false;

function onScroll() {
  if(ignoreScrollEvents) return false;
}

但是由于事件不会立即触发(oops,duhh),那不是一个可行的解决方案。我还可以尝试其他类型的答案吗?我也使用jQuery,如果这有帮助的话。

but since events don't trigger immediately (oops, duhh), that's not a workable solution. What other sort of answers could I try? I'm also using jQuery, if that helps anything.

推荐答案

最简单的通用方法?只需重置事件处理程序中的标志即可。您需要首先检查是否实际更改了值,否则将不会触发事件 - 如 Rodrigo笔记,这里的一个很好的做法是把这个分解成所谓的setter功能:

Easiest generic method? Just reset the flag in the event handler. You'll want to check first if you're actually changing the value, as otherwise an event won't be fired - as Rodrigo notes, a good practice here is to factor this out into so-called "setter" functions:

function setScrollLeft(x)
{
  if ( element.scrollLeft != x )
  {
    ignoreScrollEvents = true;
    element.scrollLeft = x;
  }
} 

...

function onScroll() 
{
  var ignore = ignoreScrollEvents;
  ignoreScrollEvents = false;

  if (ignore) return false;

  ...
}

但是,根据您的需要,您可能已经在某处存储滚动位置;如果是这样,只需更新并检查该标志即可。例如:

But, depending on your needs, you may already be storing the scroll position somewhere; if so, just update and check that as your flag. Something like:

element.scrollLeft = currentScrollLeft = x;

...

function onScroll() 
{
  // retrieve element, etc... 

  if (element.scrollLeft == currentScrollLeft) return false;

  ...
}

这篇关于使“scrollLeft” /" scrollTop"更改不会触发滚动事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆