Javascript - 跳转到 anchor 函数

标签 javascript anchor

我使用此脚本检查 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 Optional

If 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/

相关文章:

click - 使用 Protractor 查找并单击 anchor 链接

javascript - 这两个 HTML anchor 有什么区别?

javascript - 需要重构这个JS,不知道从哪里开始

php - 在 laravel 中使用动态创建的 anchor href 进行搜索

javascript - 使用 Select Option 下拉菜单的 jQuery Multiple Star Rating 系统

javascript - 将 JavaScript 注入(inject)网站

html - 固定页眉与页内 anchor 重叠

javascript - anchor 击功能在 Firefox 中不起作用

javascript - Regex 只匹配 it 和 its,不匹配 it's

javascript - 如何使用 Jscript 更改 <p> 的文本?