简体   繁体   English

JavaScript setTimeout 导致 scrollTop 事件?

[英]JavaScript setTimeout causes a scrollTop Event?

I have a collection of divs in a document that can be filtered by classname, as in hiding and showing elements.我在一个文档中有一组 div,可以按类名过滤,就像隐藏和显示元素一样。 The list can be filtered by clicking either a corresponding element in the list or one of the items in the top menu.可以通过单击列表中的相应元素或顶部菜单中的项目之一来过滤列表。

I made this pen to illustrate my problem.我做了这支笔来说明我的问题。

I call the filter function for each click event, which hide all elements, and after using window.setTimeout() I display the right ones like below.我为每个点击事件调用过滤器函数,它隐藏所有元素,并在使用window.setTimeout()显示正确的,如下所示。 This is to get a delay as well as to trigger fade-in css3-animations.这是为了获得延迟以及触发淡入 css3 动画。

var filter = function(el){

  if(filterClass==='all'){
    window.setTimeout(function(){
      $('.project').show(); //show all projects
      $('#filter-all').addClass('active');
    }, 100);
  }
  else{
    window.setTimeout(function(){
      $('.'+filterClass).show(); //show filtered projects
      $('#back2').show();
      $('#'+elClassName).addClass('active');
    }, 100);
  }  
};

The problem is that when I use window.setTimeout() the view scrolls up to the top, even if the view is in the bottom of the page.问题是,当我使用window.setTimeout() ,视图会向上滚动到顶部,即使视图位于页面底部。

Try this in the pen:用笔试试这个:

  1. Show all显示所有
  2. Scroll down to the bottom so that the top of the document is not visible in the view.向下滚动到底部,以便文档的顶部在视图中不可见。
  3. Filter by clicking some div.通过单击某个 div 进行过滤。

Result: It gets filtered correctly, but the view always scrolls/jumps up to the top.结果:它被正确过滤,但视图总是滚动/跳到顶部。

Why is this happening?为什么会这样?

I expected it to stay in the same relative scroll view when possible and otherwise end up at the bottom of the scrollbar.我希望它尽可能保持在相同的相对滚动视图中,否则最终会出现在滚动条的底部。 This is to me the standard and desired behavior.这对我来说是标准和期望的行为。

The page scrolls top because you hide elements.页面滚动顶部,因为您隐藏了元素。 So there is no more downward scrollable area.所以没有更多的向下滚动区域。 If you had 1000 items and you filtered 999 and show only 1, then what would you expect?如果您有 1000 个项目并且您过滤了 999 个并且只显示了 1 个,那么您会期望什么? The scrollable area would be way too short.可滚动区域太短了。

For your case, I would remove对于你的情况,我会删除

$(".project").hide()

And hide non-matching items only:并仅隐藏不匹配的项目:

else{
    window.setTimeout(function(){
      $('.'+filterClass).show();
      $(".project:not(" + '.' + filterClass + ')').hide();
      $('#back2').show();
      $('#'+elClassName).addClass('active');
    }, 100);
  } 

Not a perfect solution because there would be some scroll top.不是一个完美的解决方案,因为会有一些滚动顶部。 But in most cases, it would be less.但在大多数情况下,它会更少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM