以编程方式滚动到锚标记 [英] Programmatically scroll to an Anchor Tag
本文介绍了以编程方式滚动到锚标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下代码:
<a href="#label2">GoTo Label2</a>
... [content here] ...
<a name="label0"></a>More content
<a name="label1"></a>More content
<a name="label2"></a>More content
<a name="label3"></a>More content
<a name="label4"></a>More content
有没有办法模拟点击GoTo Label2"链接,通过代码滚动到页面上的适当区域?
Is there a way to emulate clicking on the "GoTo Label2" link to scroll to the appropriate region on the page through code?
EDIT:一个可接受的替代方法是滚动到具有唯一 ID 的元素,该元素已存在于我的页面上.如果这是一个可行的解决方案,我会添加锚标记.
EDIT: An acceptable alternative would be to scroll to an element with a unique-id, which already exists on my page. I would be adding the anchor tags if this is a viable solution.
推荐答案
如果你还在元素上放置了 ID,这个 JS 通常对我来说效果很好:
This JS has generally worked well for me if you also put an ID on the element:
document.getElementById('MyID').scrollIntoView(true);
这很好,因为它还可以定位可滚动的 div 等,以便内容可见.
This is good as it will also position scrollable divs etc so that the content is visible.
这篇关于以编程方式滚动到锚标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文