jQuery-平滑滚动到div [英] jQuery - smooth scroll to div

查看:77
本文介绍了jQuery-平滑滚动到div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一些代码,单击后可将页面滚动到某个元素,但在平滑滚动之前,它会跳到页面顶部.有人可以解释一下我在做什么错吗?

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 ?

这是脚本

$('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;
});

告诉我在哪里可以学习JS :)请

and tell me where can i learn JS :) please

推荐答案

这是菜单的html

<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>

这是菜单的修改脚本

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

我已经解决了我的问题,就是这样,上面的代码对我来说很完美,我把它放在这里给其他像我这样的程序员使用;),我们得到了具有url更改和平滑滚动效果的单页网站: P

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-平滑滚动到div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆