问题
This is pretty simple question I think for those who knows javascript/jquery good. I am pretty new to all this and couldn't make it. I found code that is calculating the offset of navbar that looks like this:
var offset = 50;
$('.navbar li a').click(function(event) {
event.preventDefault();
$($(this).attr('href'))[0].scrollIntoView();
scrollBy(0, -offset);
});
And here is the fiddle example of what I have so far. As you can see if you click link in navbar it just skips to section. Where in this script to add easing
so it scroll down a bit smoother?
With original code I found first I had that smooth scroll but with new script is lost. This is the old code:
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
回答1:
Plavookac Hi there.
I have set up a working sample here in this Fiddle for you.
When you place this code in your page, place it below all of you other js script links. or if you put this in a script link, place the link at the end.
I take it that you would already have the jquery link .
Have a look at this code here, you will see the smooth scrolling and the offset.
$(document).ready(function(){
// Add scrollspy to <body>
$('body').scrollspy({target: "#navbar"});
// Add smooth scrolling on all links inside the navbar
$("#navbar a").on('click', function(event) {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top - 60
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
});
});
Notice this line of code... event.preventDefault();
this is used to prevent that flicker when first clicked to start the scrolling.
This part of the code will handle the smooth scroll.
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top - 60
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
Does this help?
来源:https://stackoverflow.com/questions/32922813/simple-easing-on-bootstrap-scrollspy