window.onscroll = function() {
var oDiv = document.getElementById('div1');
var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
startMove(document.documentElement.clientHeight - oDiv.offsetHeight + scrollTop);
};
IE 有效,Firefox 無效。
document.documentElement.clientHeight 在非標準模式/不同瀏覽器表現不一致。Firefox 標準模式下 document.documentElement.clientHeight 正確,但若頁面無 DOCTYPE 或 CSS 影響,可能異常。
window.onscroll = function() {
var oDiv = document.getElementById('div1');
var viewportHeight = window.innerHeight; // 視口高度,含滾動條
var scrollTop = window.pageYOffset; // 標準滾動距離
var targetTop = viewportHeight - oDiv.offsetHeight + scrollTop;
startMove(targetTop);
};
var timer = null;
function startMove(targetTop) {
var oDiv = document.getElementById('div1');
clearInterval(timer);
timer = setInterval(function() {
var currentTop = oDiv.offsetTop;
var speed = (targetTop - currentTop) / 8; // 緩動係數
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (currentTop === targetTop) {
clearInterval(timer);
} else {
oDiv.style.top = currentTop + speed + 'px';
}
}, 30);
}
#div1 {
position: fixed;
right: 20px;
bottom: 20px;
transition: all 0.3s ease; /* 可選動畫 */
}
**結論:優先用 CSS fixed,JS 方案修正 clientHeight/scrollTop 兼容性,附緩動動畫優化。**