JS 滚轮事件实现固定在窗口某个位置的元素显现或隐藏
程序员文章站
2022-03-29 17:45:25
效果图html代码
css代码html,body{ height: 1000px;}#box{width: 100%;height: 200px;background-color: red;position: fixed;bottom: 0;display: none;}JavaScript代码//获取元素var box = document.getElementById('box');...
效果图
html代码
<div id="box"></box>
css代码
html,body{
height: 1000px;
}
#box{
width: 100%;
height: 200px;
background-color: red;
position: fixed;
bottom: 0;
display: none;
}
JavaScript代码
//获取元素
var box = document.getElementById('box');
//判断是否为火狐浏览器
//绑定滚轮事件
if (navigator.userAgent.indexOf('Firefox') != -1) {
document.addEventListener('DOMMouseScroll', wheelFun, false);
} else {
//非火狐
document.onmousewheel = wheelFun;
}
function wheelFun(event) {
//event兼容
var event = event || window.event;
//页面滚动上去的高度兼容
var top = document.documentElement.scrollTop || document.body.scrollTop;
//判断鼠标滚动方向
if (event.detail) {
if(event.detail > 0) {
console.log('向下');
} else {
console.log('向上');
}
} else if (event.wheelDelta) {
//非火狐
if (event.wheelDelta > 0) {
//console.log('向上');
top--;
} else {
//console.log('向下');
top++;
}
//简单判断 改变box的样式
if (top > 200) {
box.style.display = 'block';
} else {
box.style.display = 'none';
}
本文地址:https://blog.csdn.net/qq_43447509/article/details/107280832