鼠标滑轮滚动,页面不上下滚动,改为页面上下滑动
某天摸鱼的时候东看西看,看到了一个网站 www.wepe.com.cn/ 的首页,想要实现和它类似的效果,于是写了一个类似的前端html demo,如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* body {
overflow-y: hidden;
} */
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
html {
scroll-behavior: smooth;
}
.header {
height: 50px;
background-color: white;
color: #000;
text-align: center;
line-height: 50px;
}
.box {
overflow: hidden;
height: calc(100vh - 50px);
scroll-behavior: smooth;
}
body::-webkit-scrollbar {
display: none;
}
li {
list-style: none;
}
.big {
width: 100vw;
height: calc(100vh - 50px);
}
ul {
display: flex;
justify-content: space-between;
flex-flow: column nowrap;
position: fixed;
height: 200px;
right: 20px;
bottom: 30%;
transform: translateY(-50%);
}
ul li {
cursor: pointer;
width: 15px;
height: 15px;
border-radius: 50%;
background-color: #eee;
border: 1px solid #000;
}
.active {
background-color: #888;
}
</style>
</head>
<body>
<div class="header">
这是头部
</div>
<div class="box">
<div id="section1" class="big" style="background-color: red"></div>
<div id="section2" class="big" style="background-color: blue"></div>
<div id="section3" class="big" style="background-color: green"></div>
<div id="section4" class="big" style="background-color: yellow"></div>
<div id="section5" class="big" style="background-color: gray"></div>
</div>
<ul>
<li data-id="1" class="active"></li>
<li data-id="2"></li>
<li data-id="3"></li>
<li data-id="4"></li>
<li data-id="5"></li>
</ul>
<script>
const throttle = (fn, delay) => {
let timer = null;
return function(...args) {
if(!timer) {
fn(...args);
timer = setTimeout(() => {
timer = null;
}, delay);
}
}
}
const allCount = document.querySelectorAll('.big').length;
const ul = document.querySelector('ul');
let whichCount = 1;
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#section1').scrollIntoView(true);
})
const fn = throttle(function(e) {
const active = document.querySelector('.active');
let isDown = e.deltaY > 0;
if (whichCount < allCount && isDown) {
whichCount++;
document.querySelector(`#section${whichCount}`).scrollIntoView(true);
active.classList.remove('active');
ul.children[whichCount-1].classList.add('active');
} else if (whichCount > 1 && !isDown) {
whichCount--;
document.querySelector(`#section${whichCount}`).scrollIntoView(true);
active.classList.remove('active');
ul.children[whichCount-1].classList.add('active');
}
},1000);
window.addEventListener('wheel', fn);
ul.addEventListener('click', function(e) {
const target = e.target;
const active = document.querySelector('.active');
const id = target.dataset.id;
whichCount = +id;
active.classList.remove('active');
target.classList.add('active');
document.querySelector(`#section${whichCount}`).scrollIntoView(true);
})
</script>
</body>
</html>