Jquery Smooth Scrolling Offset
I'm making a one page site with sticky navigation on center top with width at about 1000px and height of about 20-25px, now i also included a smooth scroll function but my problem is whenever the page scrolls to it's active page, the title hid under the sticky nav, how do i get the offset of the bottom of the sticky navigation? Thanks.
This is the js code btw:
$('a').click(function(e) {
var target = $(this).attr('href');
e.preventDefault();
$('html,body').animate({
scrol开发者_JAVA技巧lTop: $(target).offset().top
}, 800, 'easeInOutCirc');
});
The easiest way to keep your current code as it is, and add that off-set to the top of your website, is by adding the needed offset value after the .top, like so:
$('a').click(function(e) {
var target = $(this).attr('href');
e.preventDefault();
$('html,body').animate({
scrollTop: $(target).offset().top - 20
}, 800, 'easeInOutCirc');
});
Hope this answer is less complicated that the last one. :)
jQuery's .position()
method will give you the top and left offsets of the element in relation to the page. So you would just need to add the .outerHeight()
of the sticky navigation to it's .position().top
value.
Here's an example: http://jsfiddle.net/NUfaZ/1/
As you scroll down in the page, you'll see it's position get updated.
Refer to https://codepen.io/pikeshmn/pen/mMxEdZ
Approach: We get the height of fixed nav using document.getElementById('header').offsetHeight And offset the scroll to this value.
var jump=function(e){
e.preventDefault(); //prevent "hard" jump
var target = $(this).attr("href"); //get the target
//perform animated scrolling
$('html,body').animate(
{
scrollTop: $(target).offset().top - document.getElementById('header').offsetHeight - 5 //get top-position of target-element and set it as scroll target
},1000,function() //scrolldelay: 1 seconds
{
location.hash = target; //attach the hash (#jumptarget) to the pageurl
});
}
$(document).ready(function()
{
$('a[href*="#"]').bind("click", jump); //get all hrefs
return false;
});
P.S:
- It includes a nice 5 pixels difference between header and target
- Scroll effect is not hard, rather smooth; Smooth Scrolling
精彩评论