Javascript 如何为 Bootstrap 的滚动间谍功能添加平滑滚动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14804941/
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
How to add smooth scrolling to Bootstrap's scroll spy function
提问by Brian
I've been trying to add a smooth scrolling function to my site for a while now but can't seem to get it to work.
一段时间以来,我一直在尝试向我的网站添加平滑滚动功能,但似乎无法使其正常工作。
Here is my HTML code relating to my navigation:
这是与我的导航相关的 HTML 代码:
<div id="nav-wrapper">
<div id="nav" class="navbar navbar-inverse affix-top" data-spy="affix" data-offset-top="675">
<div class="navbar-inner" data-spy="affix-top">
<div class="container">
<!-- .btn-navbar is used as the toggle for collapsed navbar content -->
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<!-- Everything you want hidden at 940px or less, place within here -->
<div class="nav-collapse collapse">
<ul class="nav">
<li><a href="#home">Home</a></li>
<li><a href="#service-top">Services</a></li>
<li><a href="#contact-arrow">Contact</a></li>
</ul><!--/.nav-->
</div><!--/.nav-collapse collapse pull-right-->
</div><!--/.container-->
</div><!--/.navbar-inner-->
</div><!--/#nav /.navbar navbar-inverse-->
</div><!--/#nav-wrapper-->
Here is the JS code I've added:
这是我添加的JS代码:
<script src="js/jquery.scrollTo-1.4.3.1-min.js"></script>
<script>
$(document).ready(function(e) {
$('#nav').scrollSpy()
$('#nav ul li a').bind('click', function(e) {
e.preventDefault();
target = this.hash;
console.log(target);
$.scrollTo(target, 1000);
});
});
</script>
For what it's worth, hereis where I received info on what I've done so far, and hereis my site in it's current form. If you can help me I'll bake you a pie or cookies or something. Thanks!
就其价值而言,这里是我收到有关我迄今为止所做工作的信息的地方,这里是我的网站的当前形式。如果你能帮我,我会给你烤馅饼或饼干之类的。谢谢!
回答by nice ass
Do you really need that plugin? You can just animate the scrollTopproperty:
你真的需要那个插件吗?您可以为该scrollTop属性设置动画:
$("#nav ul li a[href^='#']").on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// store hash
var hash = this.hash;
// animate
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 300, function(){
// when done, add hash to url
// (default click behaviour)
window.location.hash = hash;
});
});
回答by ahnbizcad
If you have a fixed navbar, you'll need something like this.
如果你有一个固定的导航栏,你将需要这样的东西。
Taking from the best of the above answers and comments...
从以上最佳答案和评论中汲取...
$(".bs-js-navbar-scrollspy li a[href^='#']").on('click', function(event) {
var target = this.hash;
event.preventDefault();
var navOffset = $('#navbar').height();
return $('html, body').animate({
scrollTop: $(this.hash).offset().top - navOffset
}, 300, function() {
return window.history.pushState(null, null, target);
});
});
First, in order to prevent the "undefined" error, store the hash to a variable, target, before calling preventDefault(), and later reference that stored value instead, as mentioned by pupadupa.
首先,为了防止“未定义”错误,target在调用 之前将散列存储到变量,然后preventDefault()引用该存储值,如 pupadupa 所述。
Next. You cannot use window.location.hash = targetbecause it sets the url and the location simultaneously rather than separately. You will end up having the location at the beginning of the element whose id matches the href... but covered by your fixed top navbar.
下一个。您不能使用,window.location.hash = target因为它同时而不是单独设置 url 和位置。您最终将在元素的开头找到位置,该元素的 id 与 href... 匹配,但被固定的顶部导航栏覆盖。
In order to get around this, you set your scrollTop value to the vertical scroll location value of the target minus the height of your fixed navbar. Directly targeting that value maintains smooth scrolling, instead of adding an adjustment afterwards, and getting unprofessional-looking jitters.
为了解决这个问题,您将 scrollTop 值设置为目标的垂直滚动位置值减去固定导航栏的高度。直接定位该值可以保持平滑滚动,而不是在之后添加调整,并获得看起来不专业的抖动。
You will notice the url doesn't change. To set this, use return window.history.pushState(null, null, target);instead, to manually add the url to the history stack.
您会注意到 url 没有改变。要设置它,请改用return window.history.pushState(null, null, target);手动将 url 添加到历史堆栈中。
Done!
完毕!
Other notes:
其他注意事项:
1) using the .onmethod is the latest (as of Jan 2015) jquery method that is better than .bindor .live, or even .clickfor reasons I'll leave to you to find out.
1) 使用该.on方法是最新的(截至 2015 年 1 月)jquery 方法,它比.bindor更好.live,甚至.click原因我会留给你找出来。
2) the navOffset value can be within the function or outside, but you will probably want it outside, as you may very well reference that vertical space for other functions / DOM manipulations. But I left it inside to make it neatly into one function.
2) navOffset 值可以在函数内部或外部,但您可能希望它在外部,因为您很可能会引用其他函数/DOM 操作的垂直空间。但我把它留在里面,使它整齐地成为一个功能。
回答by Marcelo Cintra de Melo
$("#YOUR-BUTTON").on('click', function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $("#YOUR-TARGET").offset().top
}, 300);
});
回答by James Akwuh
// styles.css
html {
scroll-behavior: smooth
}
Source: https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2
来源:https: //www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2
回答by escolta13
If you download the jquery easing plugin (check it out),then you just have to add this to your main.js file:
如果您下载了 jquery 缓动插件(检查出来),那么您只需要将其添加到您的 main.js 文件中:
$('a.smooth-scroll').on('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top + 20
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
and also dont forget to add the smooth-scroll class to your a tags like this:
并且不要忘记将平滑滚动类添加到您的 a 标签中,如下所示:
<li><a href="#about" class="smooth-scroll">About Us</a></li>
回答by genisugt
I combined it, and this is the results -
我把它结合起来,这就是结果——
$(document).ready(function() {
$("#toTop").hide();
// fade in & out
$(window).scroll(function () {
if ($(this).scrollTop() > 400) {
$('#toTop').fadeIn();
} else {
$('#toTop').fadeOut();
}
});
$('a[href*=#]').each(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname
&& this.hash.replace(/#/,'') ) {
var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
if ($target) {
var targetOffset = $target.offset().top;
$(this).click(function() {
$('html, body').animate({scrollTop: targetOffset}, 400);
return false;
});
}
}
});
});
I tested it and it works fine. hope this will help someone :)
我测试了它,它工作正常。希望这会帮助某人:)
回答by Patrick Hillert
What onetrickponyposted is okay, but if you want to have a more general solution, you can just use the code below.
什么onetrickpony贴是好的,但如果你想有一个更通用的解决方案,你可以使用下面的代码。
Instead of selecting just the idof the anchor, you can make it bit more standard-like and just selecting the attribute nameof the <a>-Tag. This will save you from writing an extra idtag. Just add the smoothscroll class to the navbar element.
相反,只选择的id锚的,你可以把它有点类似的标准更加公正选择属性name中的<a>-Tag。这将使您免于编写额外的id标签。只需将 smoothscroll 类添加到导航栏元素即可。
What changed
改变了什么
1) $('#nav ul li a[href^="#"]')to $('#nav.smoothscroll ul li a[href^="#"]')
1)$('#nav ul li a[href^="#"]')到$('#nav.smoothscroll ul li a[href^="#"]')
2) $(this.hash)to $('a[name="' + this.hash.replace('#', '') + '"]')
2)$(this.hash)到$('a[name="' + this.hash.replace('#', '') + '"]')
Final Code
最终代码
/* Enable smooth scrolling on all links with anchors */
$('#nav.smoothscroll ul li a[href^="#"]').on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// store hash
var hash = this.hash;
// animate
$('html, body').animate({
scrollTop: $('a[name="' + this.hash.replace('#', '') + '"]').offset().top
}, 300, function(){
// when done, add hash to url
// (default click behaviour)
window.location.hash = hash;
});
});

