admin管理员组文章数量:1325409
I use this script to check if an anchor is within the URL. If found the showscroll function get called. Only thing isn't working is the jump to the called anchor. I'm new to JS - what is wrong with the function?
In the HTML page:
<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;
} }
Edit: I can't use "scroll into view".
I use this script to check if an anchor is within the URL. If found the showscroll function get called. Only thing isn't working is the jump to the called anchor. I'm new to JS - what is wrong with the function?
In the HTML page:
<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;
} }
Edit: I can't use "scroll into view".
Share Improve this question edited Jan 16, 2012 at 21:56 Tom asked Jan 16, 2012 at 17:13 TomTom 6,00421 gold badges85 silver badges134 bronze badges1 Answer
Reset to default 6Instead of
window.location.href.match(/\#more/)
you can just do
window.location.hash == '#more'
and instead of assigning to the fragment, you can use the scrollIntoView
method as described at https://developer.mozilla/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.
本文标签: JavascriptJump to anchor functionStack Overflow
版权声明:本文标题:Javascript - Jump to anchor function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742131845a2422196.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论