當用戶經過鼠標滾輪與頁面交互、在垂直方向上滾動頁面時,就會觸發mousewheel事件,這個事件就是實現全屏切換效果須要用到的。在IE6, IE7, IE8, Opera 10+, Safari 5+中,都提供了 「mousewheel」 事件,而 Firefox 3.5+ 中提供了一個等同的事件:」DOMMouseScroll」。與mousewheel事件對應的event對象中咱們還會用到另外一個特殊屬性—wheelDelta屬性。css
一、「mousewheel」 事件中的 「event.wheelDelta」 屬性值:返回的值,若是是正值說明滾輪是向上滾動,若是是負值說明滾輪是向下滾動;返回的值,均爲 120 的倍數,即:幅度大小 = 返回的值 / 120。html
二、「DOMMouseScroll」 事件中的 「event.detail」 屬性值:返回的值,若是是負值說明滾輪是向上滾動(與 「event.wheelDelta」 正好相反),若是是正值說明滾輪是向下滾動;返回的值,均爲 3 的倍數,即:幅度大小 = 返回的值 / 3。jquery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
overflow: hidden;
}
.container {
transition: .5s;
}
.item {
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<div class="container">
<div class="item" style="background-color: rgb(255,255,0)"></div>
<div class="item" style="background-color: rgb(255, 145, 0)"></div>
<div class="item" style="background-color: rgb(0, 17, 255)"></div>
<div class="item" style="background-color: rgb(0, 255, 136)"></div>
</div>
<script src="sun.js"></script>
<script src='https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js'></script>
<script>
$(() => {
let i = 0;
let move = sun.throttle(e => {
if(e.wheelDelta < 0) {
if( i === $(".item").length - 1) return ;
i++;
} else {
if( i === 0) return;
i--;
}
$(".container").css("transform",`translateY(-${i*100}vh)`);
},500);
window.onmousewheel = move;
})
</script>
</body>
</html>
複製代碼
其中用到了節流函數throttle()
,函數代碼以下:bash
function throttle(fn,wait) {
let endTime = 0;
return function() {
if(new Date() - endTime < wait) return;
fn.apply(this,arguments);
endTime = new Date();
}
},
複製代碼