【问题标题】:Scroll to hidden element滚动到隐藏元素
【发布时间】:2025-12-03 15:10:01
【问题描述】:

我有一个隐藏的输入字段,在表 td 内,当我选择选项 A 时,我希望浏览器向下滚动到 table td 内的可见输入。 我试过下面的代码,但有些东西不正常。 输入字段ID:#id_a-1-host

jQuery('html,body').animate({scrollTop: jQuery('#id_a-1-host').offset().top},'slow');

它向下滚动但只有一点点。它没有向下滚动到输入字段。

【问题讨论】:

  • 将 id 提供给 td 本身。
  • 嗨!给 td 提供 ID 不起作用;(.
  • @Jai 你无法通过将id 提供给<td> 来导航...

标签: jquery jquery-animate


【解决方案1】:

scrollTop 基于可见性,如果您将其隐藏,使用display: none,它在视口中不可用,因此无法按预期工作。在这些情况下使用命名锚总是更好:

<a name="id-a-off" id="id-a-off">

甚至一个空的跨度也可以:

<span name="id-a-off" id="id-a-off"></span>

确保这是在静态父级中。

此外,如果您设置了静态标题或其他内容,您还需要添加该高度

jQuery('html,body').animate({
  scrollTop: jQuery('#id_a-1-host').offset().top - staticHeaderHeight
}, 'slow');

【讨论】:

  • 嗨!我在输入上有 name="id-a-off" ,但不是标签或跨度。如果我使用 staticHeaderHeight 并没有什么不同。
  • @Tony 你是如何使用staticHeaderHeight的?
  • 我测试了 var staticHeaderHeight = jQuery(window).height() - 250;
  • @Tony staticHeaderHeight = $("header").height()
  • 奇怪的是,当我打开萤火虫时它就可以工作了。很奇怪
【解决方案2】:

您可以滚动到 .closest(':visible') 元素。它进入父母,直到找到一个可见的。

提示:如果你使用 .closest() 它也包含元素本身

return $('html, body').animate({
    scrollTop: $(el).closest(':visible').offset().top
}, 400);

【讨论】: