DIV CSS 佈局教程網

JS 實作隨滾動條移動的浮動層(含關閉與回到頂部)
編輯:關於JavaScript     

浮動層是網站很常見的元素:側邊廣告、客服入口、回到頂部按鈕,都屬於這類「固定在視窗某側、跟著滾動移動」的元件。實作上要處理三件事:視窗可視區域的計算、頁碼捲動距離的取得,以及邊界判斷(避免浮動層遮住頁首或頁尾)。

下面的範例把這些細節封裝成一個 Bianyuan 工具物件,並提供 scrollBar() 函式作為主要介面。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>隨滾動條滾動的層</title>
<style>
body{ margin:0; padding:0; font-size:12px; font-family:"宋體",Arial, Helvetica, sans-serif;}
div,p,ul,ol,li,dl,dt,dd,h1,h2,h3,h4,h5,h6,form,input{ margin:0; padding:0;}
h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}
img{ border:0;}
ol,ul{list-style:none;}
a{ text-decoration:none; color:#fff;}
a:hover{ text-decoration:none;}
#scroll_div{ width:100px; height:400px; background:#990; }
#btn_close,#btn_gotop{ cursor:pointer;}
</style>
</head>
<body>
<div style="width:1002px;height:42px;margin:0 auto;background-color:#060;">頁首</div>
<div style="width:1002px;margin:0 auto;background-color:#f60;">
  這裡放主體內容,需要足夠的高度才能看到浮動層隨滾動移動的效果。
</div>
<div style="width:1002px;height:95px;margin:0 auto;background-color:#060;">頁尾</div>
<div id="scroll_div">
  <span id="btn_close">關閉</span><br />
  <span id="btn_gotop">返回頂部</span>
</div>
<script type="text/javascript">
var Bianyuan = {
  // 跨瀏覽器綁定事件(保證 this 指向 obj)
  addEvent : function (obj, type, fn) {
    if (obj.attachEvent) {
      obj['e' + type + fn] = fn;
      obj[type + fn] = function () { obj['e' + type + fn](window.event); };
      obj.attachEvent('on' + type, obj[type + fn]);
    } else {
      obj.addEventListener(type, fn, false);
    }
  },
  // 依 id 取元素
  $ : function (id) { return document.getElementById(id); },
  // 取得瀏覽器可視區尺寸
  getBrowserSize : function () {
    var pageWidth = window.innerWidth, pageHeight = window.innerHeight;
    if (typeof pageWidth != "number") {
      if (document.compatMode == "CSS1Compat") {
        pageWidth  = document.documentElement.clientWidth;
        pageHeight = document.documentElement.clientHeight;
      } else {
        pageWidth  = document.body.clientWidth;
        pageHeight = document.body.clientHeight;
      }
    }
    if (!window.ActiveXObject) { pageWidth -= 17; }  // 非 IE 扣掉滾動條寬度
    return { width : pageWidth, height : pageHeight };
  },
  // 取得滾動條目前位置
  getPageScroll : function () {
    var yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      yScroll = document.documentElement.scrollTop;
    } else if (document.body) {
      yScroll = document.body.scrollTop;
    }
    return yScroll;
  }
};

function scrollBar(scrollId, dir, headHeight, footHeight, areaWidth, o) {
  var scrollBar = Bianyuan.$(scrollId),
      barWidth  = scrollBar.offsetWidth,
      barHeight = scrollBar.offsetHeight;

  var pageWidth  = Bianyuan.getBrowserSize().width,
      pageHeight = Bianyuan.getBrowserSize().height;

  var widthMore  = document.documentElement.scrollWidth,
      heightMore = document.body.scrollHeight || document.documentElement.scrollHeight;

  var maxWidth  = Math.max(pageWidth, widthMore),
      maxHeight = Math.max(pageHeight, heightMore);

  scrollBar.style.position = 'absolute';

  // 若浮動層比整個頁面還高,直接隱藏
  if (maxHeight < (barHeight + footHeight + footHeight + 4)) {
    scrollBar.style.display = 'none';
  } else {
    // 不擋頁首
    scrollBar.style.top = Bianyuan.getPageScroll() + headHeight + 2 + 'px';
    // 接近頁尾時上移,避免遮住頁尾
    if ((heightMore - Bianyuan.getPageScroll() - barHeight) <= footHeight) {
      scrollBar.style.top = heightMore - footHeight - barHeight - 2 + 'px';
    }
  }

  // 左右定位:areaWidth 為 1 表示貼齊視窗邊緣,否則貼齊主體內容兩側
  if (dir == 'left' && areaWidth == 1) {
    scrollBar.style.left = 2 + 'px';
  } else if (dir == 'right' && areaWidth == 1) {
    scrollBar.style.left = maxWidth - barWidth - 2 + 'px';
  } else if (dir == 'left' && areaWidth != 1) {
    if (pageWidth >= (barWidth * 2 + areaWidth + 4)) {
      scrollBar.style.left = (pageWidth - areaWidth) / 2 - barWidth - 2 + 'px';
    } else {
      scrollBar.style.left = 2 + 'px';
    }
  } else if (dir == 'right' && areaWidth != 1) {
    if (pageWidth >= (barWidth * 2 + areaWidth + 4)) {
      scrollBar.style.left = (pageWidth - areaWidth) / 2 + areaWidth + 2 + 'px';
    } else {
      scrollBar.style.left = maxWidth - barWidth - 2 + 'px';
    }
  }

  // 綁定關閉與回到頂部
  if (o) {
    if (o.btnClose) {
      Bianyuan.addEvent(Bianyuan.$(o.btnClose), 'click', function () {
        scrollBar.style.display = 'none';
      });
    }
    if (o.goTop) {
      Bianyuan.addEvent(Bianyuan.$(o.goTop), 'click', function () {
        document.documentElement.scrollTop = 0;
        document.body.scrollTop = 0;
      });
    }
  }

  resizeWindow(scrollId, dir, headHeight, footHeight, areaWidth, o);
}

// 視窗尺寸改變或捲動時重新定位
function resizeWindow(scrollId, dir, headHeight, footHeight, areaWidth, o) {
  window.onresize = function () { scrollBar(scrollId, dir, headHeight, footHeight, areaWidth, o); };
  window.onscroll  = function () { scrollBar(scrollId, dir, headHeight, footHeight, areaWidth, o); };
}
</script>
<script type="text/javascript">
// 參數:元素 id、方向、頁首高度、頁尾高度、主體寬度、按鈕設定
scrollBar("scroll_div", "right", 42, 95, 1002, {btnClose:"btn_close", goTop:"btn_gotop"});
</script>
</body>
</html>

這份寫法刻意避開了 position: fixed,改用 absolute 搭配 onscroll 事件,因此能在舊版 IE 上運作。若目前的專案不必考慮舊瀏覽器,直接用 CSS 的 position: fixed 加上 transform 會更簡潔、效能也更好,因為不必在每次捲動時觸發重排。這段程式比較值得參考的是它的邊界處理邏輯——浮動元素遮擋頁尾是很常見的體驗缺陷,值得多花點心思。

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