DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> jQuery插件windowScroll實現單屏滾動特效
jQuery插件windowScroll實現單屏滾動特效
編輯:關於JavaScript     

回首望,曾經洋洋得意的代碼現在不忍直視。曾經看起來碉堡的效果現在也能稍微弄點出來。社會在往前發展,人也不得不向前走。

      參考於搜狗浏覽器4.2版本首頁的上下滾動效果。主要實現整個窗口的上下和左右滾動邏輯,還有很多可以拓展的空間。希望大家能多提意見與建議。

      代碼如下:

HTML

<!doctype html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta content="" name="keywords" />
<meta content="" name="description" />
<meta name="author" content="codetker" />
<head>
<title>window對象滾動插件</title>
<link href="style/reset.css" rel="stylesheet" type="text/css">
<link href="style/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/jquery.codetker.windowScroll.js"></script>
</head>

<body scroll="no">
  <div class="wrap" style="dispaly:block;">
    <div class="stageControl">
      <ul>
        <li>stage1</li>
        <li>stage2</li>
        <li>stage3</li>
        <li>stage4</li>
        <li>stage5</li>
      </ul>
    </div>
    <div class="stage stage1">
      <div class="pageControl">
        <ul>
          <li>page1</li>
          <li>page2</li>
          <li>page3</li>
        </ul>
      </div>
      <div class="page page1"></div>
      <div class="page page2"></div>
      <div class="page page3"></div>  
    </div>
    <div class="stage stage2"></div>
    <div class="stage stage3"></div>
    <div class="stage stage4"></div>
    <div class="stage stage5"></div>
  </div>
<script type="text/javascript">
  $(document).ready(function(){
    $(".wrap").windowScroll({
      'choose' : 0,
      'verticalSpeed' : 2, //控制垂直滾動速度
      'horizontalSpeed' : 1,
      'objControlUl': '.wrap .stageControl'
    });
    $(".stage1").windowScroll({
      'choose': 1,
      'verticalSpeed' : 1,
      'horizontalSpeed' : 1,//控制水平滾動速度
      'objControlUl': '.stage1 .pageControl'
    });
  });
</script>
</body>
</html>

CSS

@charset "utf-8";
/* CSS Document */
body{
  margin:0 0;
  padding:0 0;
  height:100%;
  width:100%;
  overflow: hidden;;
}
.wrap{
  font-family:"微軟雅黑","宋體", Times, "Times New Roman", serif;
  font-size:14px;
  margin:0 0;
  padding:0 0;
  height:100%;
  width:100%;
  overflow:hidden;
}

.stage,.page{
  width: 100%;
  height: 100%;
}
.stage1{
  background-color:red;
}
.stage2{
  background-color:#fff;
}
.stage3{
  background-color:yellow;
}
.stage4{
  background-color:green;
}
.stage5{
  background-color:blue;
}
.page{
  float: left;
}
.page2{
  background-color: #666;
}
.page3{
  background-color: #ddd;
}
.stageControl{
  position: fixed;
}
.stageControl ul li{
  width: 100px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  cursor: pointer;
}
.stageControl ul li:hover{
  color: blue;
}
.pageControl{
  position: fixed;
  left: 200px;
}
.pageControl ul li{
  float: left;
  width: 50px;
  height: 25px;
  line-height: 25px;
  text-align: center;
  cursor: pointer;
}
.pageControl ul li:hover{
  color: blue;
}

JavaScript

/*
 * windowScroll 0.1
 * window滾動插件,上下左右,可選擇是否回彈。參考搜狗歡迎頁面
 * 兼容IE,FF,Chrome等常見浏覽器
 * 借鑒搜狗4.2版http://ie.sogou.com/features4.2.html
 */
 ;(function($,window,document,undefined){
   //定義構造函數
   var WindowObj=function(ele,opt){
     this.$element=ele; //最外層對象
     this.defaults={
       'choose' : 0,//默認為上下
       'verticalSpeed' : 1,
       'horizontalSpeed' : 1,
       'objControlUl': null
     },
   
     this.options=$.extend({},this.defaults,opt );

    //阻止默認行為和冒泡,這裡可以定義多個方法都要用到的函數
    this.stopDefaultAndBubble=function(e){
      e=e||window.event;
      if (e.preventDefault) {
        e.preventDefault();
      }
      e.returnValue=false;

      if (e.stopPropagation) {
        e.stopPropagation();
      }
      e.cancelBubble=true;
    }

    this.setSize=function(ele){
      $(ele).css({
        'width':$(window).outerWidth()+'px'
      });
      //自動判斷元素是否存在,對undefined賦css屬性無意義
      $(ele).children('.stage').css({
        'width':$(window).outerWidth()+'px',
        'height':$(window).outerHeight()+'px'
      });
      $(ele).children('.page').css({
        'width':$(window).outerWidth()+'px',
        'height':$(window).outerHeight()+'px'
      });
    }
   }

   //給構造函數添加方法
   WindowObj.prototype={

     //上下滾動的方法
     verticalMove:function(){
       var obj=this.$element; //最外層對象
       var speed=this.options.verticalSpeed;
       var objControl=this.options.objControlUl;//控制按鈕

       var windowHeight=$(window).height();
       var list=$(obj).children('.stage');
       var listMax=$(list).length;

       var is_chrome=navigator.userAgent.toLowerCase().indexOf('chrome')>-1;
       if(is_chrome){
         //判斷webkit內核,供scrollTop兼容性使用
         windowobject='body';
       }else{
         //支持IE和FF
         windowobject='html';
       }
       var stop=0;

       //均設置為windows大小
       this.setSize(obj);

       //得到當前的垂直位置
       var stageIndex;
       function getIndex(){
         stageIndex=Math.round($(window).scrollTop()/windowHeight);
       } 

       //綁定鍵盤上下按鍵事件
       $(document).keydown(function(event) {
         /* 綁定keycode38,即向上按鈕 */
         if (event.keyCode==38) {
           getIndex();
          setTimeout(function(){
            scrollStage(windowobject,stageIndex,1); //stageIndex為當前頁碼
          },100);
         }else if (event.keyCode==40) {//綁定40,即向下按鈕
           getIndex();
          setTimeout(function(){
            scrollStage(windowobject,stageIndex,-1); //stageIndex為當前頁碼
          },100);
         }
       });

       //綁定滑輪功能的函數
       function handle(delta){
         getIndex();
        if (delta<0) {
          setTimeout(function(){
            scrollStage(windowobject,stageIndex,-1); //stageIndex為當前頁碼
          },100);
        }else{
          setTimeout(function(){
            scrollStage(windowobject,stageIndex,1); //stageIndex為當前頁碼
          },100);
        }

       }

       //判斷滑輪,解決兼容性
       function wheel(event){
        var delta = 0;
        if (!event) event = window.event;
        if (event.wheelDelta) {
          delta = event.wheelDelta; 
          if (window.opera) delta = -delta;
        } else if (event.detail) {
          delta = -event.detail;
        }
        if (delta)
          handle(delta); //調用執行函數
      }

       //注冊事件
       if (window.addEventListener) {
         window.addEventListener('DOMMouseScroll', wheel, false);
       }
       window.onmousewheel = document.onmousewheel = wheel;
       
       //綁定鼠標滾輪事件
       $(document).bind('mousedown', function(event) {
         if (e.which==2) {//which=2代表鼠標滾輪,即為中鍵
           this.stopDefaultAndBubble(e);
           //bugfix 搜狗浏覽器的ie內核只有在定時器觸發這個函數才生效
           setTimeout(function(){
             this.stopDefaultAndBubble(e);
           },10);
         }
       });

       //如果有ul li控制按鈕
       if (objControl!=null) {
         $(objControl).delegate('li', 'click', function() {
           stageIndex=$(this).index();
           setTimeout(function(){
             scrollStage(windowobject,stageIndex,0);
           },100);
         });
       }

       function scrollStage(obj,stIndex,dir){//如果用scrollStage=function來指定的話沒有聲明提前,然後就會找不到這個函數了
         //obj為操作滾動的對象
        //stIndex為點擊調用時應該滾動到的頁面頁碼,按鍵和滾輪調用時默認為1(傳入0)
        //dir傳入滾動時的方向,0代表不滾動,1代表向上,-1代表向下
        var sIndex=stIndex;//!(dir)則stageIndex為要到的頁碼,否則為當前頁碼
        var windowobject=obj;
        var direction=0||dir; //接收參數封裝,沒有傳入時暫時認為為0
        var target=windowHeight*sIndex; //目標頁面距離文檔頂部距離
       
        if ( !$(windowobject).is(':animated') ) {//當沒有在滾動時
          if(!direction){ ////響應guider,此時stageIndex為目標頁面頁碼
            if ($(window).scrollTop() > target) { //內容下移,窗口上移,上方出現彈痕
              direction=-1;
              $(windowobject).animate({
                "scrollTop": target +"px"
              },1000*speed,function(){
                crash_bottom(1,target,20,150); //調用撞擊函數,先撞頂部,target變成當前頁面了
              });
            }else if($(window).scrollTop() == windowHeight*sIndex){ //當前頁面時
              direction=0;
              crash_bottom(1, target ,20,150); //模擬撞底部
            }else{
              direction=1;
              $(windowobject).animate({
                "scrollTop": target +"px"
              },1000*speed,function(){
                crash(1,target,20,150); //調用撞擊函數,先撞底部

              });
            }
          }else{//響應鼠標滾輪和鍵盤上下,sindex為當前頁面
            if(direction==1){
              if(sIndex==0){
                crash(1,target,20,150);
              }else{ //往上翻
                sIndex-=1;
                $(windowobject).animate({
                  "scrollTop":windowHeight*sIndex+"px"
                  },1000*speed,function(){
                    crash_bottom(1,windowHeight*sIndex,20,150); //調用撞擊函數,往下翻內容往上,先撞頂部
                  }
                );
              }
            }else{
              if(sIndex==listMax){
                crash_bottom(1,target,20,150);
              }else{ //往下翻
                sIndex+=1;
                $(windowobject).animate({
                  "scrollTop":windowHeight*sIndex+"px"
                },1000*speed,function(){
                  crash(1,windowHeight*sIndex,20,150); //調用撞擊函數,往上翻內容往下,先撞底部
                });

              }
            }
          }
        }
       }

      //撞擊函數
      function crash_bottom(direction,termin,distant,time){
        if (!stop) {
          var scrollTop=$(window).scrollTop();
          if (direction==1) {
            direction=0;
            $(windowobject).animate({"scrollTop":"+="+distant+"px"},time,function(){
              crash_bottom(direction,termin,distant*0.6,time);
              if (distant<=15||time>150) {
                stop=1;//停止碰撞

                $(windowobject).animate({"scrollTop":termin+"px"},time,function(){
                  stop=0;
                });
              }
            });
          }else if (direction==0) {
            direction=1;
            $(windowobject).animate({"scrollTop":termin+"px"},time,function(){
              crash_bottom(direction,termin,distant*0.6,time);
              if (distant<=15||time>150) {
                stop=1;//停止碰撞

                $(windowobject).animate({"scrollTop":termin+"px"},time,function(){
                  stop=0;
                });
              }
            });
          }
        }
      }
      function crash(direction,termin,distant,time){
        if (!stop) {
          var scrollTop=$(window).scrollTop();
          if (direction==1) {
            direction=0;
            $(windowobject).animate({"scrollTop":"-="+distant+"px"},time,function(){
              crash(direction,termin,distant*0.6,time);
              if (distant<=15||time>150) {
                stop=1;//停止碰撞

                $(windowobject).animate({"scrollTop":termin+"px"},time,function(){
                  stop=0;
                });
              }
            });
          }else if (direction==0) {
            direction=1;
            $(windowobject).animate({"scrollTop":termin+"px"},time,function(){
              crash(direction,termin,distant*0.6,time);
              if (distant<=15||time>150) {
                stop=1;//停止碰撞

                $(windowobject).animate({"scrollTop":termin+"px"},time,function(){
                  stop=0;
                });
              }
            });
          }
        }
      }

     },
     //左右滾動的方法
     horizontalMove:function(){
       var obj=this.$element; //最外層對象
       var speed=this.options.horizontalSpeed;
       var objControl=this.options.objControlUl;//控制按鈕

       var windowWidth=$(window).width();
       var list=$(obj).children('.page');
       var listMax=$(list).length;

       var is_chrome=navigator.userAgent.toLowerCase().indexOf('chrome')>-1;
       if(is_chrome){
         //判斷webkit內核,供scrollTop兼容性使用
         windowobject='body';
       }else{
         //支持IE和FF
         windowobject='html';
       }
       var stop=0;

       //均設置為windows大小
       this.setSize(obj);
       $(obj).css({'width':windowWidth*listMax+'px'});

       var pageIndex; //當前頁面頁碼(負數)
      function getPageIndex(){
        pageIndex=Math.round(parseInt($(obj).css("margin-left")) / windowWidth);
      }

      //綁定鍵盤左右按鍵事件
      $(document).keydown(function(event){
        //判斷event.keyCode為39(即向右按鈕)
        if (event.keyCode==39) {
          getPageIndex();
          scrollPage($(obj),pageIndex,-1); 
        }
        //判斷event.keyCode為37(即向左按鈕
        else if (event.keyCode==37) {
          getPageIndex();
          scrollPage($(obj),pageIndex,1);
        }
      });

      //如果有ul li控制按鈕
       if (objControl!=null) {
         $(objControl).delegate('li', 'click', function() {
           pageIndex=$(this).index();
           setTimeout(function(){
             scrollPage(obj,pageIndex,0);
           },100);
         });
       }

      function scrollPage(obje,pIndex,dir){
        var windowobject=obje;
        var direction=0||dir;
        var pageIndex=pIndex;
        var dist=Math.round(parseInt($(obj).css("margin-left"))); //當前頁距離左邊的margin(負值)
        var aim=pageIndex*windowWidth*(-1);

        if (!$(windowobject).is(":animated")) {
          if(!direction){ //響應nav

            if (dist != aim) { //此時pageIndex為yearID.非負值
              $(windowobject).animate({"margin-left": aim + "px"},
                1000*speed);
            }else{
              direction=0;
              $(windowobject).animate({"margin-left":"+="+"50px"},500).animate({"margin-left":"-="+"100px"},500).animate({"margin-left":"+="+"50px"},500);
            }
          }else{ //響應鍵盤左右鍵
            if(direction==1){ //pageIndex為負值
              if(pageIndex==0){
                $(windowobject).animate({"margin-left":"+="+"50px"},500).animate({"margin-left":"-="+"100px"},500).animate({"margin-left":"+="+"50px"},500);  
              }else{
                pageIndex+=1; //顯示左邊內容,左鍵
                $(windowobject).animate({"margin-left":"+=" + windowWidth + "px"},
                  1000*speed);
              }
            }else{
              if(pageIndex== ((-1)*(listMax-1))){
                $(windowobject).animate({"margin-left":"-="+"50px"},500).animate({"margin-left":"+="+"100px"},500).animate({"margin-left":"-="+"50px"},500);  
              }else{
                pageIndex-=1;
                $(windowobject).animate({"margin-left":"-=" + windowWidth + "px"},
                  1000*speed);
              }
              
              
            }
          }
        }
      }

     }
   }

   //在插件中使用windowObj對象的方法,0為vertical,1為horizontal
   $.fn.windowScroll=function(options){
     //創建實體
     var windowObj=new WindowObj(this,options);
     //根據選擇調用方法
     if (windowObj.options.choose==0) {
       return windowObj.verticalMove();
     }else if(windowObj.options.choose==1){
       return windowObj.horizontalMove();
     }else{//2之後的留擴展吧
       //add some functions
     }
   }
 })(jQuery,window,document);

詳細的代碼下載見https://github.com/codetker/myWindowScroll

以上所述就是本文的全部內容了,希望大家能夠喜歡。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved