简体   繁体   中英

Slowly scroll to a specific div or anchor in a html page

I have an html page and I want to make it scroll slowly to a specific point or all around the page. I tried the following codes but nothing worked:

<a href="#anchorName"></a>

<script>

function scrollTo(hash) 
{
    location.hash = "#anchorName";
}

</script>

Secondly, I tried scrolling to a div but in this case I also had to use CSS and put a height. I am trying to avoid that.

As seen on stackoverflow past issues :

<a href="#myDiv" id="button">button</a>

<script>

    $("#button").click(function() 
    {
        $('html, body').animate({
            scrollTop: $("#myDiv").offset().top
        }, 2000);
    });

</script>

and it did not work at all.

Try like this :

 $(document).ready(function(){ $("#button").click(function(e) { e.preventDefault(); $('html, body').animate({ scrollTop: $($.attr(this, 'href')).offset().top }, 2000); }); }); 
 #myDiv { margin-top: 800px; height: 50px; width: 300px; background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <a href="#myDiv" id="button">button</a> <div id="myDiv"></div> 

Since you are setting #myDiv as href for the button, you have to preventDefault() before you trigger the animation:

 $("#button").click(function(e){ e.preventDefault(); $('html, body').animate({ scrollTop: $("#myDiv").offset().top }, 2000); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="myDiv" id="button">button</a> <div style="height:400px;"></div> <div id="myDiv">Lorem Ipsum</div> 

you can do a Smooth scroll to some component id by following the example codes using jQuery, for example :

<a class="move_to_div" href="#anchorName"> move div </a>


<div id="anchorName"> </div> 


<script>
 $(".move_to_div").click(function() {
  $('html, body').animate({
  scrollTop: $("#anchorName").offset().top
   }, 1000);
 });

</script>

this is just example , when click on 'a href link' the scrolldown will be smooth (to test the result add some space between a link and div by using css ) i hop this helpful for you .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM