js和jquery实现页面滚动监听

时间:2023-03-08 19:16:00
js和jquery实现页面滚动监听

js和jquery实现页面滚动监听

一、总结

一句话总结:onscroll方法和监听页面元素的高度都可以实现滚动监听。

1、onscroll方法实现滚动监听的核心代码是什么?

    <body onscroll="scroll()">

2、通过检测元素的高度实现滚动监听?

//遍历楼层
jumbotron.each(function() {
var $this = $(this),
jumbotronTop =$this.offset().top;//获取当前楼层的高度
if (top > (jumbotronTop - 200)) {
currentID = "#" + $this.attr("id");//每个小于top的楼层都会赋值一次,逐层覆盖替换,最后一层才是最后的id值
}
else {
return false;
};
})

二、onscroll方法实现滚动监听

js监听html页面的上下滚动事件

最近在一个项目中,在写前端页面的时候,想像以前做Android时在页面时刻监听上下滚动的事件,查找资料发现由鼠标或类似用户动作触发的事件有以下图示:

js和jquery实现页面滚动监听

不多说了,直接上代码了,经过测试可以使用:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Dome</title>
<script type="text/javascript"> function scroll(){
//console.log("打印log日志");实时看下效果
console.log("开始滚动!");
} var scrollFunc = function (e) {
e = e || window.event;
if (e.wheelDelta) { //第一步:先判断浏览器IE,谷歌滑轮事件
if (e.wheelDelta > 0) { //当滑轮向上滚动时
console.log("滑轮向上滚动");
}
if (e.wheelDelta < 0) { //当滑轮向下滚动时
console.log("滑轮向下滚动");
}
} else if (e.detail) { //Firefox滑轮事件
if (e.detail> 0) { //当滑轮向上滚动时
console.log("滑轮向上滚动");
}
if (e.detail< 0) { //当滑轮向下滚动时
console.log("滑轮向下滚动");
}
}
}
//给页面绑定滑轮滚动事件
if (document.addEventListener) {//firefox
document.addEventListener('DOMMouseScroll', scrollFunc, false);
}
//滚动滑轮触发scrollFunc方法 //ie 谷歌
window.onmousewheel = document.onmousewheel = scrollFunc; </script> </head>
<body onscroll="scroll()">
<div style="height: 2000px;background-color: aqua;"></div>
</body>
</html>

如果有没有使用过console.log(“”)的,我这里截下图看下吧(谷歌浏览器):
js和jquery实现页面滚动监听

三、通过检测元素的高度实现滚动监听

jQuery实现滚动监听

1.设计思路
1)获取窗口滚动高度;
2)获取附加导航栏;
3)获取导航栏下的所有li;
4)通过相同class获取所有监听元素;(此例中为jumbotron巨幕)
5)遍历所有监听元素,若当前元素距离文档高度小于文档滚动条的垂直偏移量(即滚动高度),获取当前元素ID。(此处获取的ID值,实际为ID值覆盖替换,因为存在有多个元素的e当前元素距离文档高度小于文档滚动条的垂直偏移量的情况,但只有最后的ID是有效值,因
为前边的会被后边的覆覆盖替换掉)
6)给对应的导航添加class(bootstrap中为给li添加active),先移出已有的active,然后再添加。

实现代码
$(document).ready(function() {
//定义全局变量,获取附加导航栏、导航列表、链接、各楼层、各楼层距离文档的高度
var menu = $("#add-nav"),
lists = menu.find("li"),
jumbotron = $(".jumbotron"),
currentID;
$(window).scroll(function() {
//获取文档滚动高度
var top = $(document).scrollTop(); //遍历楼层
jumbotron.each(function() {
var $this = $(this),
jumbotronTop =$this.offset().top;//获取当前楼层的高度
if (top > (jumbotronTop - 200)) {
currentID = "#" + $this.attr("id");//每个小于top的楼层都会赋值一次,逐层覆盖替换,最后一层才是最后的id值
}
else {
return false;
};
})
//给相应楼层对应的附加到导航添加class
//首先清除所有active
var currentActive = menu.find(".active");
if (currentID && currentActive.find("a:eq(0)").attr("href") != currentID) {
currentActive.removeClass("active"); //给相应导航添加class
menu.find("[href="+currentID+"]").parent().addClass("active");
}
}) });

用到的方法有:scroll()、scrollTop()、offset()、attr()、addClass()、removeClass()、find()、each()、parent()
其中重点说明:.offset()内容相对于文档的偏移(不是浏览器窗口),所以可以理解为固定值;