题
请考虑以下代码:
<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的元素,该元素已存在于我的页面上。如果这是一个可行的解决方案,我会添加锚标签。
解决方案
如果您还在元素上添加了ID,那么这个JS通常对我有用:
document.getElementById('MyID').scrollIntoView(true);
这很好,因为它也会定位可滚动的div等,以便内容可见。
其他提示
使用javascript:
window.location.href = '#label2';
如果您需要从后面的服务器/代码执行此操作,您只需发出此Javascript并将其注册为该页面的启动脚本。
从服务器端移动到锚点,例如c#。
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#form';", true);
我想这会奏效:
window.location="<yourCurrentUri>#label2";
解决方案
document.getElementById('MyID').scrollIntoView(true);
几乎在所有浏览器中运行良好,而我注意到在某些浏览器或某些移动设备(例如某些Blackberry版本)中,“scrollIntoView”功能无法识别,所以我会考虑这个解决方案(比前一个有点丑):
window.location.href = window.location.protocol + "//" + window.location.host +
window.location.pathname + window.location.search +
"#MyAnchor";
如果元素是锚标记,您应该能够:
document.getElementsByName('label2')[0].focus();
不是“#”当你使用window.location.hash
时您只需打开附加名称的新网址,例如 http://www.example.com/mypage.htm#label2
在JavaScript中,
location.href = location.href + '#label2';
不隶属于 StackOverflow