jQuery动画滚动不起作用

jQuery Animated Scroll Not Working

本文关键字:不起作用 滚动 动画 jQuery      更新时间:2023-09-26

我正在尝试让jQuery动画滚动函数工作,以便当用户单击按钮时,它可以很好地向下滚动。我已经完成了几个教程,但我无法让动画工作。当我单击按钮时,它会跳到相应的区域,但它是突然的,没有任何动画。这是我的代码:

j查询:

<script>
    $(function() {
       $('a[href*=#]:not([href=#])').click(function() {
          if (location.pathname.replace(/^'//,'') == this.pathname.replace(/^'//,'') &&  location.hostname == this.hostname) {
             var target = $(this.hash);
             target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
             if (target.length) {
                $('html,body').animate({
                   scrollTop: target.offset().top
                }, 1000);
             return false;
             }
           }
       });
   });
</script>  

.HTML:

<ul class="list-inline intro-social-buttons">
   <li><a href="#moreinfo" class="btn btn-default btn-lg"><i class="fa fa-rocket fa-fw"></i> <span class="network-name">Learn More</span></a>
   </li>
</ul>

然后以后:

<div class="content-section-a" id="moreinfo">

jquery-1.10.2.js 和 jQuery.min.map 都链接并加载没有问题。我做错了什么??

这可能是问题所在:

target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

HTML 锚点的默认值是跳转到名称/id 在"#"之后的元素。

如下所示:http://jsfiddle.net/avBst/1/

这可能意味着您的目标变量实际上没有返回一个项目,并且 jQuery 动画代码根本没有触发。


以下是简单的代码,用于滚动到id为"at_bottom"的指定div,并链接到顶部。

http://jsfiddle.net/xUs6g/4/

更多"一刀切"的答案:

http://jsfiddle.net/UGfDj/1/

解释:

创建具有自定义属性的链接:

<a class="scroll_to" data-more-info="section_one">Go To Section One</a>

和具有匹配 ID 的div

<div id="section_one" class="section">

单击该链接后,提取属性值并滚动到具有该 ID 的div。

$("a.scroll_to").click(function() {
  var target = $(this).attr("data-more-info");
  $("html, body").animate({ scrollTop: $("#"+target).offset().top - 50 }, "slow");
  return false;
});

-50 用于抵消小提琴中的上边距。您可能不需要它。

这样,您无需为所有滚动按钮等编写单击功能。

有一个简单的CSS解决方案,但并非在所有浏览器上都可用。我推荐一个jquery答案,但这是一个巧妙的css技巧,挽救了我的生命,我倾向于分享:)

html,body {
    scroll-behavior: smooth;
}