如何使网页加载时首先显示您希望用户首先看到的锚点所在部分?
这是否可能?
提前感谢您所有的帮助。
这样简单的东西就可以做到。
<body onload=' location.href="#myanchor" '>
<a id='myanchor' href='#'>anchor text</a>
这里是一个比较动态的 2018 年更新。
如果你想要获取 URL,提取锚点并将页面移至该锚点,你可以在页面加载时运行以下 JavaScript 代码。
if (window.location.href.indexOf('#') == 0) {
let hash = window.location.href.split('#')[1];
let hashTop = document.querySelector(`#${hash}`).offsetTop;
window.scrollTop = hashTop;
}
if (location.hash) {
let target = location.hash;
window.scrollTop = document.querySelector(target).offsetTop;
}
如果你没有使用babel编译ES6,只需将let
关键字更改为var
即可。 这也适用于WordPress,在锚点之前会在URL中添加斜杠。
使用 JavaScript。
解决方案1
当文档加载时,转到您想要的“哈希”或锚点。
<script type="text/javascript">
function load()
{
window.location.hash="mylocation";
}
</script>
解决方案2
在头文件中:
<script type="text/javascript" language="javascript">
function moveWindow (){window.location.hash="mylocation";}
</script>
标签上:
<body onload="moveWindow()">
And your anchor:
<a name="mylocation"></a
>
<script type="text/javascript">
window.addEventListener('load', function() {
if (location.hash) location.href = location.hash;
});
</script>
这些答案的混合最终对我来说是最好的选择,并且具有动态性,通过从URL中提取锚点并强制页面加载到预期目标:
if (location.hash) location.href = location.hash;
这是我的项目中最干净的解决方案,因为有许多其他的东西在onload时运行:
JQuery:
$(window).on("load", function() {
if (location.hash) location.href = location.hash;
}
原味:
window.addEventListener('load', function() {
if (location.hash) location.href = location.hash;
}