DIV CSS 佈局教程網

JS 實現隨頁面滾動的懸浮分享工具條
編輯:JavaScript綜合知識     

側邊懸浮的分享按鈕幾乎是內容站的標配。它不會老老實實待在文檔流裡,而是隨著頁面滾動一直懸浮在可視區的垂直中心位置;鼠標移上去還會滑出來。本文拆解實現方式。

核心計算:垂直居中

var scrtop = document.documentElement.scrollTop || document.body.scrollTop;
var height = document.documentElement.clientHeight || document.body.clientHeight;
var top = scrtop + (height - jb51.offsetHeight) / 2;
top = parseInt(top);

可視區高度減去元素高度再除以二,得到元素相對於可視區的偏移量;再加上當前滾動距離,就換算成了文檔坐標下的 top 值。最後取整,避免出現小數坐標。

完整代碼

<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title>懸浮分享工具條</title>
<style>
  body { margin:0; padding:0; font:12px/1.5 arial; height:2000px; }
  #jb51 {
    width:100px; height:200px; line-height:200px; text-align:center;
    border:1px solid #ccc; background:#f5f5f5;
    position:absolute; left:-100px; top:0;
  }
  #jb51_tit {
    position:absolute; right:-20px; top:60px;
    width:20px; height:60px; padding:10px 0;
    background:#06c; text-align:center;
    line-height:18px; color:#fff;
  }
</style>
<script>
window.onload = function () {
  var jb51 = document.getElementById("jb51");

  jb51.onmouseover = function () { startrun(jb51, 0, "left"); };
  jb51.onmouseout  = function () { startrun(jb51, -100, "left"); };

  // 滾動與窗口尺寸變化時都重新計算位置
  window.onscroll = window.onresize = function () {
    var scrtop = document.documentElement.scrollTop || document.body.scrollTop;
    var height = document.documentElement.clientHeight || document.body.clientHeight;
    var top = scrtop + (height - jb51.offsetHeight) / 2;
    top = parseInt(top);
    startrun(jb51, top, "top");
  };
};

var timer = null;
function startrun(obj, target, direction) {
  clearInterval(timer);
  timer = setInterval(function () {
    var speed = 0;
    if (direction == "left") {
      speed = (target - obj.offsetLeft) / 8;
      speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
      if (obj.offsetLeft == target) {
        clearInterval(timer);
      } else {
        obj.style.left = obj.offsetLeft + speed + "px";
      }
    }
    if (direction == "top") {
      speed = (target - obj.offsetTop) / 8;
      speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
      if (obj.offsetTop == target) {
        clearInterval(timer);
      } else {
        obj.style.top = obj.offsetTop + speed + "px";
      }
    }
  }, 30);
}
</script>
</head>
<body>
  <div id="jb51">
    分享到內容
    <span id="jb51_tit">分享到</span>
  </div>
</body>
</html>

這裡用同一個 startrun 函數同時處理 left 和 top 兩個方向,靠 direction 參數分流。實戰中建議改用 position: fixed,可以省掉 scroll 事件裡的坐標換算,性能也更友好。

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