長頁面裡,分享按鈕放在最上面,讀到一半就找不到;固定死在角落又會擋內容。常見的折衷做法是讓它「跟著捲動」,並且垂直置中於當前視窗——這就是本文要做的事。
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);
拆開來看:height - jb51.offsetHeight 是「視窗剩下的空白」,除以 2 就是上下各留一半;再加上 scrtop 換算成文件座標。少了 scrtop,元素只會停在文件頂端附近,捲動時不會跟著走。
<!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>
這裡把 onscroll 和 onresize 綁在一起是對的:視窗尺寸改變時,置中位置也得重算。
效能上要留意:scroll 事件觸發得非常密集,每次都跑一次 30ms 的緩動動畫會造成明顯卡頓。實務上有兩個更好的選擇——一是直接用 position:fixed 讓瀏覽器合成層處理,程式碼幾乎不用寫;二是保留 JS 但改用 requestAnimationFrame 並在 scroll 回呼中做节流(throttle)。這裡的緩動版本,是為了示範「座標換算」這個核心觀念。