url中没有id的内部链接

Internal link without id in url

本文关键字:内部 链接 id url      更新时间:2023-09-26

如果我们需要跳到顶部,那么我们可以简单地编写一个代码

<a href="#top">link to top</a>

或者只是javascript代码

location.href=#top

结果:它将我们带到带有url的首页:http://fiddle.jshell.net/_display/#top.

但我的问题是,我不想在url字符串上显示/#top查询,但我希望我的页面位于顶部。我不想在url中显示该字符串的原因是,如果浏览器找不到名为top的"id",我的页面就会被卡住。我显示的上下文或信息在对话框中,因此一旦对话框关闭,当用户尝试刷新该页面时,即http://fiddle.jshell.net/_display/#top,页面被卡住。

有人能给这个问题一个更好的解决方案吗?

您有几个选项。。。

您可以使用纯Javscript:

window.scrollTo(X, Y);(显然X和Y是滚动坐标,顶部为0,0)。

另一个选项(但不是基于jQuery)可以是:

document.body.scrollTop = document.documentElement.scrollTop = 0;

如果您更喜欢基于jQuery的解决方案,请尝试以下方法:

$(document).scrollTop(0);

或者:

$(window).scrollTop(0);

使用更适合您需要的选项。

享受编码。

尝试

$(".link").on("click", function(e) {
  $("body").animate({scrollTop: $(".link").not(this).offset().top}, 500);
  return false
})
#top, #bottom {
  height:400px;
  width:100%;
  display:block;
}
div:nth-of-type(1) {
  background:blue;
}
div:nth-of-type(2) {
  background:orange;
}
span {
  background:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="top">top <span class="link">go to bottom</span></div>
<div id="bottom">bottom <span class="link">go to top</span></div>

此处演示

Html

 <div id="div1" style="height: 1000px; width 100px">
    Test
</div>
<br/>
<div id="div2" style="height: 1000px; width 100px">
    Test 2
</div>
<button id="click">Click me</button>

Jquery

 $(document).ready(function (){
            $("#click").click(function (){
                //$(this).animate(function(){
                    $('html, body').animate({
                        scrollTop: $("#div1").offset().top
                    }, 2000);
                //});
            });
        });