简体   繁体   中英

How to make this scroll to div script “smooth”

So I found this script by a user of this site however I can't remember the author. The script is working, however I want it to scroll more "smoothly" than just instantly appear at my desired information. And if possible, have the destination appear 300pixels above the div.

How do I do that?

 #general{ margin-top:900px; height: 100px; weight: 100px; background: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> var hashTagActive = ""; $(".scroll").click(function (event) { if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll. event.preventDefault(); //calculate destination place var dest = 0; if ($(this.hash).offset().center > $(document).height() - $(window).height()) { dest = $(document).height() - $(window).height(); } else { dest = $(this.hash).offset().center; } //go to destination $('html,body').animate({ scrollTop: dest }, 2000, 'swing'); hashTagActive = this.hash; } }); </script> <div> <a class="scroll" href="#general">Hello</a> </div> <div id="general"> </div 

For a smoother scroll you can use:

$(document).ready(function() {
  $("ANCHOR LINK").click(function(event){     
    event.preventDefault();
    $("html, body").animate({scrollTop:$(this.hash).offset().top}, 1000);
  });
});

And you see the last number? 1000 , make it bigger to make it slower.

The second thing I'm afraid I can't help you with.

For smooth scroll to 300px above top of the element, your JavaScript function should look like this :

$(".scroll").click(function (event) {
    $('html,body').animate({
        scrollTop: ($(this.hash).offset().top - 300)
    }, 2000);
    event.preventDefault();
});

How to animate to #id links:

jsfiddle

HTML

<a href="#content">Click me!</a><br>
<a href="google.com">Google.com</a>
<div id="content"></div>

CSS

#content {
    margin-top: 900px; 
    height: 100px; width: 100px;
    background-color: lightgreen;
}

jQuery

$('a').on('click', function (event) {
    var target = $(this.hash),
        top;

    if (target) {
        top = target.offset().top;

        event.preventDefault();

        $('html, body').animate({
            scrollTop: top
        }, 600, 'swing');
    }
});

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