简体   繁体   中英

How to add smooth scrolling to a div

I know there are already answers to this, but I searched and none is working and I don't know why.

So what I wanted is a smooth scroll to a div by the tag

What I wanted was like this

So I took the js code but on me isn't working at all, the scroll loses his effect at all.

Here is my code: w HTML

<div class="col-lg-3 col-md-3 col-sm-3" id="some">
        <a href="#info" id="normal">
            <img src="imgs/product/normal.png" class="img-responsive">
        </a>
</div>

<!-- OTHER CONTENT -->

<div id="info">     
                Go here
</div>

And the JS:

$("#some a[href^='#']").on('click', function(e) {
  // prevent default anchor click behavior
  e.preventDefault();
  // animate
  $('html, body').animate({
    scrollTop: $(this.hash).offset().top
  }, 300, function() {
    // when done, add hash to url
    // (default click behaviour)
    window.location.hash = this.hash;
  });
});

I don't know if you copy > paste your code but you're missing a quote before the id:

<div class="col-lg-3 col-md-3 col-sm-3 id="some">

That could be a solution why it's not working because $('#some a') doesn't exist then.

That is before you have a link inside. BTW look at your console, is there any error messages?

Change your code to:

$("#some a").on('click', function(e) {

   // prevent default anchor click behavior
   e.preventDefault();

   e.stopImmediatePropagation();
   e.stopPropagation();
   var id = $(this).attr("href");
   // animate
   $('html, body').animate({
       scrollTop: $(id).offset().top
     }, 300, function(){

       // when done, add hash to url
       // (default click behaviour)
       window.location.hash = this.hash;
     });

});

Just use below code snippet to achieve as you mentioned in post.

$(function() {
  $('a').bind('click',function(event){
     var $anchor = $(this);
     $('html, body').stop().animate({
        scrollTop: $($anchor.attr('href')).offset().top
     }, 1000);       
      event.preventDefault();
   });
});

check DEMO

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