1. 程式人生 > >滑鼠滾動一次就是一屏

滑鼠滾動一次就是一屏

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<style type="text/css">
    html, body {  height: 100%;  }
    body, ul, li, a, p, div {
        padding: 0px;
        margin: 0px;
        font-size: 14px;
    }
    #wrap {
        overflow: hidden;
        width: 100%;
    }
    #main {
        height: 2944px;
        top: 0;
        position: relative;
    }
    .page {
        width: 100%;
        margin: 0;
    }
    #page1 {
        background: #E4E6CE;
    }
    #page2 {
        background: #6CE26C;
    }
    #page3 {
        background: #BF4938;
    }
    #page4 {
        background: #2932E1;
    }
</style>
<body>
<div id="wrap">
    <div id="main">
        <div id="page1" class="page">page1</div>
        <div id="page2" class="page">page2</div>
        <div id="page3" class="page">page3</div>
        <div id="page4" class="page">page4</div>
    </div>
</div>
</body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
    var wrap = document.getElementById("wrap");
    var main = document.getElementById("main");
    var hei = document.body.clientHeight;
    wrap.style.height = hei + "px";
    var obj = document.getElementsByTagName("div");
    for (var i = 0; i < obj.length; i++) {
        if (obj[i].className == 'page') {
            obj[i].style.height = hei + "px";
        }
    };
    //如果不加時間控制,滾動會過度靈敏,一次翻好幾屏
    var startTime = 0, //翻屏起始時間
        endTime = 0,
        now = 0;
    //瀏覽器相容
    if ((navigator.userAgent.toLowerCase().indexOf("firefox") != -1)) {
        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);
//mousewheel事件中的 “event.wheelDelta” 屬性值:返回的如果是正值說明滾輪是向上滾動

//DOMMouseScroll事件中的 “event.detail” 屬性值:返回的如果是負值說明滾輪是向上滾動
        if ((endTime - startTime) < -1000) {
            if (delta > 0 && parseInt(main.offsetTop) > -(hei * 3)) {
//向下滾動
                now = now - hei;
                toPage(now);
            }
            if (delta < 0 && parseInt(main.offsetTop) < 0) {
//向上滾動
                now = now + hei;
                toPage(now);
            }
            endTime = new Date().getTime();
        }
        else {
            event.preventDefault();
        }
    }
    function toPage(now) {
        $("#main").animate({top: (now + 'px')}, 1000);     //jquery實現動畫效果
    }

</script>
</html>