JavaScript - 跳转到锚点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5694686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:29:30  来源:igfitidea点击:

JavaScript - Jump to anchor

javascriptanchor

提问by Michael

I'm trying to open a div with a jump to the anchor. The opening part is working but it's not jumping to the named anchor

我试图打开一个跳转到锚点的 div。开头部分正在工作,但没有跳转到命名锚点

This is my script:

这是我的脚本:

<script type="text/javascript">
    function spoil(id){
        if (document.getElementById) {
            var divid = document.getElementById(id);
            divid.style.display = (divid.style.display = 'block');
            window.location = '#' + id;
        }
    }
</script>

<a href="http://example.com" onclick="spoil('thanks');" title="hello">
    <img src="images/gfx.png" alt="world" width="300" height="300"/>
</a>

Any ideas what's wrong with it? Cheers.

任何想法有什么问题?干杯。

采纳答案by Alex K.

Looks like you're unhiding a spoiler div. If so, you can scroll the element into view as follows:

看起来您正在取消隐藏剧透 div。如果是这样,您可以将元素滚动到视图中,如下所示:

function spoil(id) {
    var divid = document.getElementById(id);
    divid.style.display = 'block';
    divid.scrollIntoView(true);
    return false;
}
...
<a href="#" onclick="return spoil('thanks');" title="hello"><img src="images/gfx.png" alt="world" width="300" height="300"/></a>

回答by jammon

Did you try window.location.hash = '#'+id;?

你试了window.location.hash = '#'+id;吗?