之前用fullpage插件做过全屏滚动的页面,今天用js自己实现了一下,还蛮简单的.
首先html结构为
[html] view plain copy
- <div id="wrap">
- <div id="main">
- <div id="page1" class="page"></div>
- <div id="page2" class="page"></div>
- <div id="page3" class="page"></div>
- <div id="page4" class="page"></div>
- </div>
- </div>
wrap块为窗口可看到的部分,我们可以通过js获取窗口可视区的大小,并为其设置overflow: hidden属性,使得窗口不出现滚动条,只显示窗口大小的一页内容;
设置main定位为relative,通过改变main块的top属性实现不同页面的切换,具体的css代码如下:
[css] view plain copy
- html,body{
- margin: 0;
- padding: 0;
- }
- #wrap{
- width: 100%;
- overflow: hidden;
- background: #ccc;
- }
- #main{
- width: 100%;
- background: #ccc;
- position: relative;
- }
- .page{
- width:100%;
- margin:0;
- }
- #page1{
- background:#E4E6CE;
- }
- #page2{
- background:#6CE26C;
- }
- #page3{
- background:#BF4938;
- }
- #page4{
- background:#2932E1;
- }
js代码的主要部分就是对滚动事件的函数绑定,大多数浏览器提供了 “mousewheel” 事件,Firefox 3.5+不支持,但支持相同作用的事件:”DOMMouseScroll”;
mousewheel事件“event.wheelDelta” 属性值:返回的如果是正值说明滚轮是向上滚动;
DOMMouseScroll事件“event.detail” 属性值:返回的如果是负值说明滚轮是向上滚动;每页高度为document.body.clientHeight+’px’;
具体代码如下:
[javascript] view plain copy
- var pages = document.getElementsByClassName("page");
- var wrap = document.getElementById("wrap");
- var len = document.documentElement.clientHeight;
- var main = document.getElementById("main");
- wrap.style.height = len + "px";
- for(var i=0; i<pages.length; i++){
- pages[i].style.height = len + "px";
- }
- if(navigator.userAgent.toLowerCase().indexOf("firefox") != -1){
- document.addEventListener("DOMMouseScroll",scrollFun);
- }else if(document.addEventListener){
- document.addEventListener("mousewheel",scrollFun,false);
- }else if(document.attachEvent){
- document.attachEvent("onmousewheel",scrollFun);
- }else{
- document.onmousewheel = scrollFun;
- }
- var startTime = 0;
- var endTime = 0;
- var now = 0;
- function scrollFun(e){
- startTime = new Date().getTime();
- var event = e || window.event;
- var dir = event.detail || -event.wheelDelta;
- if(startTime - endTime > 1000){
- if(dir>0 && now > -3*len){
- now -= len;
- main.style.top = now +"px";
- endTime = new Date().getTime();
- }else if(dir<0 && now < 0){
- now += len;
- main.style.top = now +"px";
- endTime = new Date().getTime();
- }
- }else{
- event.preventDefault();
- }
- }
原文地址:https://www.cnblogs.com/mm2015/p/9095212.html
时间: 2024-11-09 17:13:08