首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JS 右下角跟隨懸浮框:跨瀏覽器兼容性修復(clientHeight/scrollTop)

     編輯:程式設計綜合問答

問題代碼

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.innerHeight + window.pageYOffset

window.onscroll = function() {
  var oDiv = document.getElementById('div1');
  var viewportHeight = window.innerHeight; // 視口高度,含滾動條
  var scrollTop = window.pageYOffset;      // 標準滾動距離
  var targetTop = viewportHeight - oDiv.offsetHeight + scrollTop;
  startMove(targetTop);
};

startMove 優化(緩動動畫)

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);
}

現代最佳:CSS position: fixed

#div1 {
  position: fixed;
  right: 20px;
  bottom: 20px;
  transition: all 0.3s ease; /* 可選動畫 */
}
  • 零 JS,瀏覽器原生合成層渲染,性能最高、最流暢。
  • IE9+ 全支持,移動端完美。
  • 若需舊 IE 支持,保留 JS 方案作為 Polyfill。

**結論:優先用 CSS fixed,JS 方案修正 clientHeight/scrollTop 兼容性,附緩動動畫優化。**

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved