萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

CSS position:fixed 水平滾動時固定定位失效的解決方案:JS 同步 left/right 實現垂直固定、水平跟隨

問題本質

`position: fixed` 元素相對 **視窗** 定位。頁面出現**水平滾動條**時,fixed 元素**不會**隨水平滾動移動,導致:

  • 左側固定欄被內容遮擋或超出視窗
  • 右側固定欄與內容錯位

期望行為:**垂直方向 fixed(不隨垂直滾動)、水平方向 absolute(隨水平滾動)**。

核心算法

// 目標:元素相對視窗左邊固定 offsetLeft
// 滾動時:newLeft = originalLeft - scrollX

// 目標:元素相對視窗右邊固定 offsetRight  
// 滾動時:newRight = originalRight + scrollX - (documentWidth - viewportWidth)
// 推導:視窗右邊 = scrollX + viewportWidth
// 文檔右邊 = documentWidth
// 元素距文檔右邊 = documentWidth - (elementLeft + elementWidth)
// 固定距視窗右邊 = originalRight
// → elementLeft = scrollX + viewportWidth - originalRight - elementWidth
// 簡化:newRight = originalRight - (scrollX - (documentWidth - viewportWidth))
// 即:newRight = originalRight - max(0, scrollX - (docWidth - viewWidth))

完整 jQuery 插件實現(原文重構優化)

;(function ($) {
  'use strict';
  
  $.ScrollFixed = function (el, options) {
    const base = this;
    base.$el = $(el);
    base.el = el;
    base.$window = $(window);
    base.$document = $(document);
    
    base.options = $.extend({}, $.ScrollFixed.defaultOptions, options);
    
    // 記錄初始 left/right(解析為數值)
    const style = window.getComputedStyle(base.el);
    base.originalLeft = parseFloat(style.left) || 0;
    base.originalRight = parseFloat(style.right) || 0;
    base.fixedSide = base.options.fixed; // 'left' | 'right'
    
    // 確保元素是 fixed 定位
    base.$el.css('position', 'fixed');
    
    base._bindEvents();
    base._updatePosition(); // 初始定位
  };
  
  $.ScrollFixed.prototype = {
    _bindEvents() {
      const base = this;
      // 使用 passive listener 提升滾動性能
      base.$window.on('scroll.scrollFixed resize.scrollFixed', 
        $.throttle ? $.throttle(16, base._updatePosition.bind(base)) : base._throttledUpdate.bind(base)
      );
    },
    
    _throttledUpdate() {
      if (this._ticking) return;
      this._ticking = true;
      requestAnimationFrame(() => {
        this._updatePosition();
        this._ticking = false;
      });
    },
    
    _updatePosition() {
      const base = this;
      const scrollLeft = base.$window.scrollLeft();
      const viewportWidth = base.$window.width();
      const docWidth = base.$document.width();
      const maxScrollX = Math.max(0, docWidth - viewportWidth);
      const clampedScrollX = Math.min(scrollLeft, maxScrollX);
      
      if (base.fixedSide === 'left') {
        // 左側固定:left = originalLeft - scrollX(但不小於 0)
        const newLeft = Math.max(0, base.originalLeft - clampedScrollX);
        base.$el.css('left', newLeft + 'px');
      } else if (base.fixedSide === 'right') {
        // 右側固定:right = originalRight + (scrollX - maxScrollX) 但不超過 originalRight
        // 等價:right = originalRight - max(0, maxScrollX - scrollLeft)
        const newRight = base.originalRight - Math.max(0, maxScrollX - clampedScrollX);
        base.$el.css('right', newRight + 'px');
      }
    },
    
    destroy() {
      this.$window.off('.scrollFixed');
      this.$el.css({ position: '', left: '', right: '' });
    }
  };
  
  $.ScrollFixed.defaultOptions = {
    fixed: 'left' // 'left' 或 'right'
  };
  
  $.fn.scrollFixed = function (options) {
    return this.each(function () {
      const plugin = new $.ScrollFixed(this, options);
      $(this).data('scrollFixed', plugin);
    });
  };
  
  // 簡易 throttle(若未引入 underscore/lodash)
  if (!$.throttle) {
    $.throttle = function (wait, fn) {
      let last = 0;
      return function (...args) {
        const now = Date.now();
        if (now - last >= wait) {
          last = now;
          fn.apply(this, args);
        }
      };
    };
  }
  
})(jQuery);

使用示例

<style>
#leftSidebar { position: fixed; left: 20px; top: 100px; width: 200px; background: #fff; box-shadow: 0 2px 8px rgba(0,0,0,.1); }
#rightSidebar { position: fixed; right: 20px; top: 100px; width: 200px; background: #fff; box-shadow: 0 2px 8px rgba(0,0,0,.1); }
</style>

<div id="leftSidebar">左側固定導航</div>
<div id="rightSidebar">右側客服面板</div>

<script>
$(function () {
  $('#leftSidebar').scrollFixed({ fixed: 'left' });
  $('#rightSidebar').scrollFixed({ fixed: 'right' });
});
</script>

原生 JS 版(無依賴、更輕量)

class ScrollFixed {
  constructor(el, { fixed = 'left' } = {}) {
    this.el = el;
    this.fixed = fixed;
    this.originalLeft = parseFloat(getComputedStyle(el).left) || 0;
    this.originalRight = parseFloat(getComputedStyle(el).right) || 0;
    
    el.style.position = 'fixed';
    this._boundUpdate = this._update.bind(this);
    window.addEventListener('scroll', this._boundUpdate, { passive: true });
    window.addEventListener('resize', this._boundUpdate, { passive: true });
    this._update();
  }
  
  _update() {
    const scrollX = window.scrollX;
    const vw = window.innerWidth;
    const docW = document.documentElement.scrollWidth;
    const maxScrollX = Math.max(0, docW - vw);
    const clamped = Math.min(scrollX, maxScrollX);
    
    if (this.fixed === 'left') {
      this.el.style.left = Math.max(0, this.originalLeft - clamped) + 'px';
    } else {
      this.el.style.right = this.originalRight - Math.max(0, maxScrollX - clamped) + 'px';
    }
  }
  
  destroy() {
    window.removeEventListener('scroll', this._boundUpdate);
    window.removeEventListener('resize', this._boundUpdate);
    this.el.style.position = this.el.style.left = this.el.style.right = '';
  }
}

// 使用
new ScrollFixed(document.getElementById('leftSidebar'), { fixed: 'left' });
new ScrollFixed(document.getElementById('rightSidebar'), { fixed: 'right' });

現代 CSS 方案(實驗性/未來標準)

/* CSS Anchor Positioning (Chrome 125+ 實驗性) */
.fixed-el {
  position: fixed;
  position-anchor: --main-content;
  left: anchor(--main-content left); /* 相對錨點定位 */
}

/* Container Queries + sticky(部分場景可替代) */
@container (min-width: 800px) {
  .sidebar { position: sticky; top: 100px; }
}

結語

`position:fixed` 水平滾動失效是經典難題。**JS 同步 left/right 是當前最穩健的跨瀏覽器方案**;核心公式:`left固定: newLeft = max(0, originalLeft - scrollX)`、`right固定: newRight = originalRight - max(0, maxScrollX - scrollX)`。封裝為可復用插件/類,配合 `requestAnimationFrame` 節流與 `passive` 監聽器,可獲得流暢體驗。未來可期待 CSS Anchor Positioning 徹底解決此問題。

copyright © 萬盛學電腦網 all rights reserved