jQuery - smooth scroll to div

2019-08-22 07:52发布

问题:

Hi i've wrote some code that scrolls page to an element after click but before smooth scroll it jumps to the top of the page. Can someone explain me what i'm doing wrong ?

this is the script

$('a[href*="#"]').click(function(e){
        e.preventDefault();
    if($(this).attr('href') == '#') {
       $('html, body').animate({
        scrollTop: $('body').offset().top
       }, 1000);
       window.location.hash = '';
    } else {
        $('html, body').animate({
            scrollTop: $( $.attr(this, 'href') ).offset().top - $(this).height()
        }, 1000);   
        window.location.hash = $(this).attr('href');
    }
        return false;
});

and tell me where can i learn JS :) please

回答1:

This tutorial and demo shows how to achieve that. Take a look at it. http://css-tricks.com/snippets/jquery/smooth-scrolling/



回答2:

this is html of menu

<div class="menu">
  <div class="top">
    <ul class="menu_list">
      <li><a href="#">Start</a></li>
      <li><a href="#o_nas">About</a></li>
      <li><a  href="#services">Services</a></li>
      <li><a href="#portfolio">Portfolio</a></li>
      <li><a href="#contact">Contact</a></li>
     </ul>
  </div>
</div>

This is modified script for the menu

//menu smooth scroll to element
    $('a[href^="#"]').on('click',function(e){
        $target = $(this).attr('href');
       e.preventDefault();
        $('.active').removeClass('active');
        $(this).addClass('active');
        if($(this).attr('href') == '#') {

           $('html, body').stop().animate({
            scrollTop: $('body').offset().top
           }, 1000, function(){location.hash = $target;});
        } else {
            $('html, body').stop().animate({
                scrollTop: $($target).offset().top + 57 - $('.menu').height() 
//this is important to add + height of menu holder div in my case it's 57 this removes jump effect in firefox
            }, 1000,function(){location.hash = $target});

        }
        return false;
    });

i've solved my question and this is it, the above code works perfect to me and i'm putting it here for other programmers like me ;) and we got the single page site with url change and smooth scrolling effect :P



标签: jquery scroll