这篇文章主要介绍了怎么使用原生javascript实现的全屏滚动功能,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
具体如下:
原理:
1. 计算当前浏览器屏幕高度,每次翻页显示的内容高度即为屏幕高度
2. 对鼠标滚轮事件进行监听,注意滚轮事件的浏览器兼容问题。
废话不多说,直接上代码
html代码:
<div id="wrap">
<div id="main" >
<div class="content num1">
<img src="https://cache.yisu.com/upload/information/20200622/114/64924.jpg" width="100%" height="100%">
</div>
<div class="content num2">
<img src="https://cache.yisu.com/upload/information/20200622/114/64928.jpg" width="100%" height="100%">
</div>
<div class="content num3">
<img src="https://cache.yisu.com/upload/information/20200622/114/64929.jpg" width="100%" height="100%">
</div>
<div class="content num4">
<img src="https://cache.yisu.com/upload/information/20200622/114/64930.jpg" width="100%" height="100%">
</div>
</div>
</div>
css代码:
#wrap{overflow: hidden;width: 100%;}
#main{top: 0;position: relative;}
.content{width: 100%;margin: 0;height: 100%;}
.num1{background: #e8e8e8;}
.num2{background: pink;}
.num3{background: yellow;}
.num4{background: orange;}
js代码:
<script type="text/javascript">
var wrap = document.getElementById("wrap");
var divHeight = window.innerHeight;
wrap.style.height = divHeight + "px";
var content = $(".content");//懒得写获取类的原生js代码了,直接用了jquery,=。=
content.height(divHeight);
var startTime = 0, //开始翻屏时间
endTime = 0,
now = 0;
if ((navigator.userAgent.toLowerCase().indexOf("firefox")!=-1)){
//for firefox;
document.addEventListener("DOMMouseScroll",scrollFun,false);
}
else if (document.addEventListener) {
document.addEventListener("mousewheel",scrollFun,false);
}
else if (document.attachEvent) {
document.attachEvent("onmousewheel",scrollFun);
}
else{
document.onmousewheel = scrollFun;
}
//滚动事件处理函数
function scrollFun(event){
startTime = new Date().getTime();
var delta = event.detail || (-event.wheelDelta);
if ((endTime - startTime) < -1000) {
//1秒内执行一次翻页
if (delta > 0 && parseInt(main.style.top) > -divHeight * ( content.length - 1)) { //向下翻页
now += divHeight ;
turnPage(now);
}
if (delta < 0 && parseInt(main.style.top) < 0) { //向上翻页
now -= divHeight ;
turnPage(now);
}
endTime = new Date().getTime();
}
else{
event.preventDefault();
}
}
//翻页函数
function turnPage(now){
$("#main").animate({top:(-now+'px')},1000);
//懒得写动画代码了,直接用了jquery,=。=
}
</script>
感谢你能够认真阅读完这篇文章,希望小编分享的“怎么使用原生javascript实现的全屏滚动功能”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。