我使用此脚本检查 URL 中是否有 anchor 。如果找到,将调用 showscroll 函数。 唯一不起作用的是跳转到被调用的 anchor 。 我是 JS 新手 - 该函数有什么问题?
在 HTML 页面中:
<script type="text/javascript">
<!--
function checkurl(){
if (window.location.href.match(/\#more/))
{
showscroll('more');
}
if (window.location.href.match(/\#tab2/))
{
showscroll('tab2');
}
}
//-->
</script>
</head>
<body onload="checkurl()">
.JS
function showscroll(id){
if (document.getElementById) {
var divid = document.getElementById(id);
divid.style.display = divid.style.display='block';
// NOT WORKING:
window.location.href = "#"+id;
//
return false;
} }
编辑:我不能使用“滚动到 View ”。
最佳答案
代替
window.location.href.match(/\#more/)
你可以这样做
window.location.hash == '#more'
而不是分配给片段,您可以使用 scrollIntoView
方法,如 https://developer.mozilla.org/en/DOM/element.scrollIntoView 中所述。
Summary
The
scrollIntoView()
method scrolls the element into view.Syntax
element.scrollIntoView(alignWithTop);
alignWithTop
OptionalIf true, the scrolled element is aligned with the top of the scroll area. If false, it is aligned with the bottom.
Note: By default, the element is scrolled to align with the top of the scroll area.
关于Javascript - 跳转到 anchor 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8883651/