javascript 如何滚动到具有特定 div 类的第一个可见元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12591466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:36:11  来源:igfitidea点击:

How can I scroll to first visible element with a specific div class?

javascriptjqueryscroll

提问by user962642

Is there anyway to automatically scroll to the first visible element with a certain div class using javascript?

无论如何使用javascript自动滚动到具有某个div类的第一个可见元素?

thanks!

谢谢!

回答by Blender

You should be able to use something like this:

你应该能够使用这样的东西:

$('html, body').animate({
    scrollTop: $('.class:visible:first').offset().top
}, 1000);

Demo: http://jsfiddle.net/Blender/xUw54/2/

演示:http: //jsfiddle.net/Blender/xUw54/2/

回答by tsi

Can be easily done with plain JS:

可以用普通的 JS 轻松完成:

const items = container.getElementsByClassName('active');
if (items.length > 0) {
  container.scrollTo({
    top: items[0].offsetTop,
    behavior: 'smooth'
  });
}

This assumes:

这假设:

  • containeris your scrollable container, you can replace with document& windowif you're trying to scroll the whole page.
  • You're looking for the first item with an activeclass name.
  • You'd like a smooth scroll, remove the behavior: 'smooth'config if you want the scroll to happen instantly in a single jump.
  • container是您的可滚动容器,如果您要滚动整个页面documentwindow则可以用&替换。
  • 您正在寻找具有active类名的第一项。
  • 你想要一个平滑的滚动,behavior: 'smooth'如果你希望滚动在一次跳跃中立即发生,请删除配置。

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo