效果描述
- 側邊固定區塊(如「分享到」),頁面滾動時**垂直居中**跟隨
- 滑鼠懸停 → 向右滑出展開內容
- 滑鼠離開 → 向左滑回收縮
- 窗口縮放時實時重新計算居中位置
核心座標計算
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var clientH = document.documentElement.clientHeight || document.body.clientHeight;
var targetTop = scrollTop + (clientH - el.offsetHeight) / 2;
targetTop = parseInt(targetTop); // 取整避免抖動
完整代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312">
<title>滾動懸浮</title>
<style>
body { margin: 0; padding: 0; font: 12px/1.5 Arial; height: 2000px; }
#floatBox {
width: 100px; height: 200px; line-height: 200px; text-align: center;
border: 1px solid #ccc; background: #f5f5f5; position: absolute; left: -100px; top: 0;
}
#floatTab {
position: absolute; right: -20px; top: 60px; width: 20px; height: 60px;
padding: 10px 0; background: #06c; text-align: center; line-height: 18px; color: #fff; cursor: pointer;
}
</style>
</head>
<body>
<div id="floatBox">
分享到內容
<span id="floatTab">分享到</span>
</div>
<script>
var box = document.getElementById('floatBox');
var timer = null;
window.onload = function() {
box.onmouseover = function() { startRun(this, 0, 'left'); };
box.onmouseout = function() { startRun(this, -100, 'left'); };
window.onscroll = window.onresize = function() {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var clientH = document.documentElement.clientHeight || document.body.clientHeight;
var top = scrollTop + (clientH - box.offsetHeight) / 2;
startRun(box, parseInt(top), 'top');
};
};
function startRun(el, target, dir) {
clearInterval(timer); // 全局單 timer(簡化版,多元素需掛元素上)
timer = setInterval(function() {
var speed = 0;
if (dir === 'left') {
speed = (target - el.offsetLeft) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (el.offsetLeft === target) { clearInterval(timer); }
else el.style.left = el.offsetLeft + speed + 'px';
}
if (dir === 'top') {
speed = (target - el.offsetTop) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (el.offsetTop === target) { clearInterval(timer); }
else el.style.top = el.offsetTop + speed + 'px';
}
}, 30);
}
</script>
</body>
</html>
改進建議
- 每元素獨立 timer:
el.timer 替代全局 timer,避免多組件衝突。
- CSS fixed + transform:現代瀏覽器用
position: fixed; top: 50%; transform: translateY(-50%); 純 CSS 實現垂直居中跟隨,無需 JS 監聽 scroll/resize。
- 節流 scroll/resize:
requestAnimationFrame 或 lodash.throttle 降低計算頻率。
- 展開動畫用 CSS transition:
#floatBox { transition: left .3s; },JS 只切換 class。
適用場景
- 側邊客服、分享工具條、返回頂部、在線咨詢入口
- 需兼容 IE8- 的老項目(fixed 不支援時需 JS 方案)