Internal link without id in url

ぐ巨炮叔叔 提交于 2019-12-24 03:16:07

问题


If we need to jump to top section then we can simple write a code

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

or just javascript code

location.href=#top

Result : It takes us to top page with url :http://fiddle.jshell.net/_display/#top.

But what my problem is, I dont' want to show /#top query on url string but i want my page to that top section . Reason why i don't want to show that string in url is, my page get stuck if browser don't find 'id' named top .Context or information which i'm displaying is inside a dialog box so that once the dialog box is closed there isn't any id named top then when user tries to refresh that page i.e http://fiddle.jshell.net/_display/#top , page gets stuck .

Can anyone give a better solution for this problem?


回答1:


Try

$(".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>



回答2:


You have few options...

You can use pure Javscript:

window.scrollTo(X, Y); (obvisourly X and Y are the scroll coordinates, and top will be 0,0).

Another option (yet non-jQuery based) can be:

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

If you prefer jQuery based solution, try the following:

$(document).scrollTop(0);

Or, as well:

$(window).scrollTop(0);

Use the option that better suit your need.

Enjoy coding.




回答3:


Demo Here

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);
                //});
            });
        });


来源:https://stackoverflow.com/questions/29113990/internal-link-without-id-in-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!