;(function() {
function hScroll(options) {
var self = this;
//$.extend(defaults, options);
self = Object.assign(self, {
nav1: '', //导航栏
nav2: '', //需要监听的内容
check: '', //选中样式
}, options);
self.init();
}hScroll.prototype = {
init: function() {
var self = this,
arr = [],
kdiv = $(self.nav2);
for(var i = 0; i < kdiv.length; i++) {
arr.push($(kdiv[i]).offset().top);
}
self.sctopFun(arr);
$(window).scroll(function(e) {
self.sctopFun(arr);
});
$(self.nav1).click(function(e) {
$('body,html').animate({
scrollTop: arr[$(this).index()] + 'px'
});
});
},
sctopFun: function(arr) {
var self = this;
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset;
var keys = 0,
flag = true;
for(var i = 0; i < arr.length; i++) {
keys++;
if(flag) {
if(scrollTop >= arr[arr.length - keys] - 300) {
$(self.nav1).eq(arr.length - keys).addClass(self.checkClass).siblings().removeClass(self.checkClass);
flag = false;
} else {
flag = true;
}
}
}
},
}
window.hScroll = hScroll;
}());
html代码
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.headv {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 140px;
z-index: 10;
}
.headv>div {
float: left;
padding: 20px;
cursor: pointer;
}
.headv-check {
border-bottom: 1px solid red;
}
</style>
<div class="x12 headv">
<div>导航1</div>
<div>导航2</div>
<div>导航3</div>
<div>导航4</div>
<div>导航5</div>
</div>
<div class="x12 nav-list">
<div class="nav1 x12" style="background: turquoise;height: 500px;"></div>
<div class="nav2 x12" style="background: yellow;height: 800px;"></div>
<div class="nav3 x12" style="background: teal;height: 1000px;"></div>
<div class="nav4 x12" style="background: tan;height: 500px;"></div>
<div class="nav5 x12" style="background: thistle;height: 1200px;"></div>
</div>
//初始化
new hScroll({
nav1: '.headv>div', //导航对应的元素
nav2: '.nav-list>div', //监听的元素
checkClass: 'headv-check' //选中的样式
});