以编程方式滚动到锚标记
考虑以下代码:
<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”链接滚动到页面上的相应区域?
编辑:一个可接受的替代方案是滚动到具有唯一 ID 的元素,该元素已存在于我的页面上。 如果这是一个可行的解决方案,我将添加锚标记。
Consider the following code:
<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
Is there a way to emulate clicking on the "GoTo Label2" link to scroll to the appropriate region on the page through code?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果你还在元素上放置一个 ID,这个 JS 通常对我来说效果很好:
这很好,因为它还可以定位可滚动的 div 等,以便内容可见。
This JS has generally worked well for me if you also put an ID on the element:
This is good as it will also position scrollable divs etc so that the content is visible.
使用 javascript:
如果您需要从服务器/后台代码执行此操作,您只需发出此 Javascript 并将其注册为该页面的启动脚本即可。
Using javascript:
If you need to do it from the server/code behind, you can just emit this Javascript and register it as a startup script for that page.
从服务器端转移到锚点,示例是 c#。
Moving to a anchor from server side, example is c#.
我想这会起作用:
I suppose this will work:
该解决方案
在几乎所有浏览器中都运行良好,而我注意到在某些浏览器或某些移动设备(例如某些黑莓版本)中“scrollIntoView”功能无法识别,所以我会考虑这个解决方案(比以前的有点难看)一):
The solution
works well in almost all browsers, whereas I've noticed that in some browsers or in some mobile (such as some Blackberry versions) "scrollIntoView" function is not recognized, so I would consider this solution (a bit uglier than the previous one):
如果该元素是锚标记,您应该能够执行以下操作:
If the element is an anchor tag, you should be able to do:
使用 window.location.hash 时没有“#”
no "#" when you use window.location.hash
您只需打开附加名称的新 URL,例如
http://www.example.com/mypage.htm#label2
在 JavaScript 中,
you can just open the new URL with the name appended, for instance
http://www.example.com/mypage.htm#label2
In JavaScript,