Bootstrap scrollspy - how to set offset and smooth transition to each section with Jquery or JavaScript?
我想做的是设置scrollspy的偏移量,并使其平滑过渡到每个部分。我宁愿不使用插件或数据属性(如果需要数据属性则可以),但是我想要一个采用以下javascript并添加平滑动画滚动效果的解决方案。 jQuery解决方案(如果可能)。
Scrollspy可以使用此代码,而offset可以使用以下代码:
可能有人可以接受此代码并将其添加到其中以设置平滑过渡吗?
1 2 3 4 5 6 7 | var offset = 60; $('.navbar li a').click(function(event) { event.preventDefault(); $($(this).attr('href'))[0].scrollIntoView(); scrollBy(0, -offset); }); |
我的HTML / CSS代码设置如下:
我有一个容器div,其类为.main-content。这是在css中设置的,边距将其与我的页眉和页脚偏移,页眉和页脚固定在顶部和底部,高度分别为60px。
1 | .main-content {position: realtive; width: 100%; height: 100%; margin: 60px 0 60px 0;} |
我在.main-content中有几个部分,每个部分都有一个id = " ... ",HTML看起来像这样。我已经删除了所有内容,因此您可以清楚地看到这些部分。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <section id="top" class="top"> ... </section> <section id="services" class="services"> ... </section> <section id="portfolio" class="portfolio"> ... </section> <section id="pricing" class="pricing"> ... </section> <section id="faq" class="faq"> ... </section> <section id="quote" class="quote"> ... </section> |
我正在使用的菜单具有如下结构:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <button class="dl-trigger">Open Menu</button> <ul class="dl-menu"> <li> BACK TO TOP </li> <li> OUR SERVICES </li> <li> OUR PORTFOLIO </li> <li> FAQ </li> <li> GET YOUR QUOTE </li> </ul> |
我对Jquery / JavaScript还是很陌生,并尝试了所有可以找到的解决方案,但没有找到适合我的布局的解决方案。如果有人可以帮助我解决这个问题,我将不胜感激!
在弄乱leuan答案中的内容之后,这个脚本开始变得有意义了,我能够结合从您在答案中提供的链接中找到的一些信息,这似乎适用于我正在使用的设置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | $(".dl-menu li a[href^='#']").on('click', function(e) { // This sets the hash var target; target = this.hash; // Prevent default anchor click behavior e.preventDefault(); // The grabs the height of my header var navOffset; navOffset = $('#header').height(); // Animate The Scroll $('html, body').animate({ scrollTop: $(this.hash).offset().top - navOffset }, 600, function(){ // Adds hash to end of URL return window.history.pushState(null, null, target); }); }); |
我要感谢leuan的所有帮助,因为正是他的帮助使我找到了解决方案。我希望这能像我一样对其他人有用。
这是小提琴-https://jsfiddle.net/wptjzbno/4/
好像您正在使用此答案中的代码。
该答案还指出,无法简单地更改由Bootstrap完成的滚动平滑。
我建议您从此答案中尝试其他解决方案,例如下面的代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 $("#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;
});
});fiddle