JavaScript 平滑滚动不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23430918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:51:51  来源:igfitidea点击:

JavaScript Smooth Scroll not working

javascriptjqueryhtml

提问by Kondax Design

I'm attempting to create a smooth scrolling page, but it seems to not work. If I remove the smooth scrolling aspect of my site, the anchor automatically jumps to the div element like usual.

我正在尝试创建一个平滑的滚动页面,但它似乎不起作用。如果我删除网站的平滑滚动方面,锚点会像往常一样自动跳转到 div 元素。

I have attached a JSFiddle: http://jsfiddle.net/J7sxD/5/

我附上了一个 JSFiddle:http: //jsfiddle.net/J7sxD/5/

var $root = $('html, body');
$('a').click(function() {
    $root.animate({
        scrollTop: $( $(this).attr('href') ).offset().top
    }, 500);
    return false;
});

回答by Timur

remove overflow-x: hidden;and it will work

删除 overflow-x: hidden;它会起作用

See here http://jsfiddle.net/acidrat/Wt2rp/1/

见这里http://jsfiddle.net/acidrat/Wt2rp/1/

回答by Matt Wilson

Taylor, your jsfiddle sample worked just fine for me, but I'll share an easier way to do the smooth scroll. Use jQuery and the jQuery.localScroll plugin.

泰勒,您的 jsfiddle 示例对我来说效果很好,但我将分享一种更简单的方法来进行平滑滚动。使用 jQuery 和 jQuery.localScroll 插件。

Download the latest smoothscroll.js: https://github.com/flesler/jquery.localScroll/releases

下载最新的smoothscroll.js:https: //github.com/flesler/jquery.localScroll/releases

Add the two javascript references:

添加两个 javascript 引用:

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="javascript/smoothscroll.js"></script> 

Then make sure to add the class "smoothScroll" to your <a>links, like this:

然后确保将类“smoothScroll”添加到您的<a>链接中,如下所示:

<a href="#anchor1" class="smoothScroll">Jump to Page Location</a>