编程滚动到锚点标签

44

考虑以下代码:

<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
是否有一种通过代码模拟点击“转到Label2”链接来滚动到页面上适当区域的方法?
编辑:如果在我的页面上已经存在具有唯一ID的元素,则滚动到该元素将是可接受的替代方案。 如果这是可行的解决方案,我将添加锚标签。

相似问题 https://dev59.com/aGw15IYBdhLWcg3wWqf- - Michael Freidgeim
8个回答

76

如果您在元素上也放置了一个ID,则此JS对我来说通常运行良好:

document.getElementById('MyID').scrollIntoView(true);

这很好,因为它还会定位可滚动的div等,使内容可见。


11

使用 JavaScript:

window.location.href = '#label2';

如果您需要从服务器/后端代码执行此操作,您只需发出此JavaScript并将其注册为该页面的启动脚本即可。


这对我非常有效,但仍然需要使用锚点。WebBrowser控件嵌入在WinForms应用程序中。 - FastAl

3

从服务器端移动到锚点,例如使用C#。

ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#form';", true);

2

我想这个会起作用:

window.location="<yourCurrentUri>#label2";

1

解决方案

document.getElementById('MyID').scrollIntoView(true);

这种方法在几乎所有的浏览器中表现良好,但是我注意到有些浏览器或者一些移动设备(例如某些Blackberry版本)无法识别"scrollIntoView"函数,因此我认为这个解决方案会略显丑陋:

window.location.href = window.location.protocol + "//" + window.location.host + 
                       window.location.pathname + window.location.search + 
                       "#MyAnchor";

1

如果该元素是锚点标签,您应该能够执行以下操作:

document.getElementsByName('label2')[0].focus();

你的代码有错误 - 应该是document.getElementsByName。来源 - https://dev59.com/LWsz5IYBdhLWcg3wj4kc - Imants Volkovs

0

使用window.location.hash时不要加“#”


-1

您可以通过在名称后附加新的URL来打开它,例如http://www.example.com/mypage.htm#label2

在JavaScript中,

location.href = location.href + '#label2';

如果您执行多次,这会出现错误吗?http://www.mysite.com/mypage.htm#label2#label2 - EndangeredMassa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接