最近看到全屏滾動切換,就想自己寫一個,但是發現一個小問題!那就是大神們寫的都太簡單了,不是太簡了。小白的我無法看懂!
自己找了一些相關的知識,做了一個,只不過代碼就,你懂的
html代碼:
<div></div> <div></div> <div></div> <div></div>
css代碼:
*{margin: 0;padding: 0;} body{ overflow: hidden; } div{ height: 100vh; } div:nth-child(1){ background: #2932E1; } div:nth-child(2){ background: #6CE26C; } div:nth-child(3){ background: #BF4938; } div:nth-child(4){ background: yellow; }
javascript代碼:
var switch = true; //控制開關,讓在運動之后才能再次檢測鼠標滾動,不然就運動錯誤 document.DOMMouseScroll = function(){ //瀏覽器兼容問題 if(switch == true){ //檢測完成,后讓switch為false,不讓再次檢測鼠標滾動 switch = false; test(); } } document.onmousewheel = function(){ //瀏覽器兼容問題 if(switch == true){ switch = false; test(); } }
function test(){
var e = e || event;
if(e.wheelDelta > 0 || e.detail < 0 ){ //檢測鼠標滾動方向
motion2();
}
if(e.wheelDelta < 0 || e.detail > 0 ){
motion();
}
}
function motion(){
clearInterval(time2);
var totalHeight = document.documentElement.scrollHeight; //全文高度
var screenHeight = document.documentElement.clientHeight; //屏幕高度
var weltPosition = document.documentElement.scrollTop; //初始化的滾動條位置
var i = 1; //滾動方向(1:向上,-1:向下)
var targetPosition = weltPosition + screenHeight * i; //目標滾動位置:滾動條位置 + 屏幕高度
var time2 = setInterval( function(){
document.documentElement.scrollTop = weltPosition + i*40; //滾動條的位置:初始化位置加上40速度
i++;
if(document.documentElement.scrollTop >= targetPosition){
document.documentElement.scrollTop = targetPosition;
switch = true; //運動結束后清除定時器,並把switch設為true,能檢測是否滾動鼠標
clearInterval(time2);
}
if(targetPosition == totalHeight){ //如果滾動條位置==目標位置,就讓目標位置減去屏幕高度(滾動條位置等0顯示的是第一屏,而目標位置等於屏幕高度,//所以最后一屏的目標為本市文本高度,但是顯示的話,確實少一屏
document.documentElement.scrollTop = targetPosition - screenHeight;
switch = true;
clearInterval(time2);
}
},30)
}
function motion2(){
clearInterval(time);
var totalHeight = document.documentElement.scrollHeight; //全文高度
var screenHeight = document.documentElement.clientHeight; //屏幕高度
var weltPosition = document.documentElement.scrollTop; //滾動條位置
var i = -1;
var targetPosition = weltPosition + screenHeight*i;
var time = setInterval( function(){
document.documentElement.scrollTop = weltPosition + i*40;
i--;
if(document.documentElement.scrollTop <= targetPosition){
document.documentElement.scrollTop = targetPosition;
switch = true;
clearInterval(time);
}
if(document.documentElement.scrollTop <= 0 ){
document.documentElement.scrollTop = 0;
switch = true;
clearInterval(time);
}
},30)
}
這樣子就完成了,但是代碼明顯很臃腫,技能方面的不足,請見諒!
更希望將來,自己能不斷的完善,估計更多使用的是插件吧!
