DIV CSS 佈局教程網

原生 JS 實現百葉窗效果及原理詳解
編輯:關於JavaScript     

百葉窗效果大家應該都不陌生,先看一下示意圖:

原理

如下圖所示,空心格子就好比每個 li,給它設定相對定位並設置 overflow:hidden;黑色區塊是 li 的子元素,高度設為 li 的兩倍,採用 absolute 定位。我們要做的,就是改變它的 top 值來獲得翻動的變化。

佈局分析

注意 top 值的變化:默認 top=0 時顯示「上鋪」;當 top 變為負值(例如 -40px)時,子元素上移,於是顯示的就變成了「下鋪」。特別要注意包裹 p 元素的那層 div。

JS 分析

1、需要開啟多個定時器來達到效果;

2、運動方向相反;

3、執行多組運動;

4、透過累加產生錯落感;

5、產生時間間隔的動畫。

window.onload = function(){
  var oUl = document.getElementById('ul1');
  var oUl2 = document.getElementById('ul2');
  toShow(oUl);
  setTimeout(function(){ toShow(oUl2); }, 4000);
  function toShow(obj){
    var aDiv = obj.getElementsByTagName('div');
    var iNow = 0, timer = null, bBtn = true;
    setInterval(function(){ toChange(); }, 2000);
    function toChange(){
      timer = setInterval(function(){
        if(iNow==aDiv.length){ clearInterval(timer); iNow = 0; bBtn = !bBtn; }
        else if(bBtn){ startMove(aDiv[iNow], {top:0}); iNow++; }
        else{ startMove(aDiv[iNow], {top:-30}); iNow++; }
      }, 100);
    }
  }
};
//運動框架
function startMove(obj, json, endFn){
  clearInterval(obj.timer);
  obj.timer = setInterval(function(){
    var bBtn = true;
    for(var attr in json){
      var iCur = parseInt(getStyle(obj, attr)) || 0;
      var iSpeed = (json[attr] - iCur) / 8;
      iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
      if(iCur != json[attr]) bBtn = false;
      obj.style[attr] = iCur + iSpeed + 'px';
    }
    if(bBtn){ clearInterval(obj.timer); if(endFn){ endFn.call(obj); } }
  }, 30);
}
//獲取非行間樣式
function getStyle(obj, attr){
  if(obj.currentStyle){ return obj.currentStyle[attr]; }
  else{ return getComputedStyle(obj, false)[attr]; }
}

以上就是原生 JS 實現百葉窗效果的完整原理與程式碼,希望對大家有所幫助。

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