height() 获取的是元素不包含padding、border、margin的高度
outerHeight() 获取的是元素包含padding、border,不包含margin的高度
outerHeight(true) 获取的是元素包含padding、border、margin的高度
offset() 返回的是匹配元素相对于当前可视窗口的偏移坐标,返回的对象中包括2个整型属性top和left(此方法对可见元素有效)
可以看到,元素的border和padding都是0,所以 height() 和 outerHeight() 相等
右侧的导航栏,滑动到对应的位置,高亮对应的导航栏
// nav
var NAVS = ['cont1', 'cont2', 'cont3', 'cont5', 'cont6']
// 判断导航在1440分辨率下或在头部时隐藏
$(function(){
if($(window).width() < 1440){
$('.nav').hide();
} else {
$(window).scroll(function(){
var top = $(this).scrollTop();
if(top < 895){
$('.nav').fadeOut();
} else {
$('.nav').fadeIn();
}
NAVS.forEach(function(nav, idx){
var navoffset = $('#'+nav).offset();
var navheight = $('#'+nav).outerHeight();
if (navoffset.top <= top && top < navoffset.top + navheight) {
$('.nav li').removeClass('on').eq(idx).addClass('on');
}
})
})
}
});
//锚点
$('.nav a[href*=#]').click(function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var $target = $(this.hash);
$target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
if ($target.length) {
var targetOffset = $target.offset().top;
$('html,body').animate({
scrollTop: targetOffset
}, 500);
return false;
}
}
});