萬盛學電腦網

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

CSS background-attachment:fixed 實現視差滾動佈局完整教程

效果預覽

頁面分為多個全屏 Section,每個 Section 固定一張大圖背景。滾動時背景圖保持固定(`background-attachment: fixed`),內容上滑覆蓋,產生視差沉浸感。右側固定導航指示當前 Section,點擊平滑滾動。

HTML 結構

<div id="cbp-fbscroller" class="cbp-fbscroller">
  <nav>
    <a href="#fbsection1" class="cbp-fbcurrent">Section 1</a>
    <a href="#fbsection2">Section 2</a>
    <a href="#fbsection3">Section 3</a>
    <a href="#fbsection4">Section 4</a>
    <a href="#fbsection5">Section 5</a>
  </nav>
  <section id="fbsection1"><div class="content">內容 1</div></section>
  <section id="fbsection2"><div class="content">內容 2</div></section>
  <section id="fbsection3"><div class="content">內容 3</div></section>
  <section id="fbsection4"><div class="content">內容 4</div></section>
  <section id="fbsection5"><div class="content">內容 5</div></section>
</div>

核心 CSS

/* 1. 所有父級高度 100% */
html, body,
.container,
.cbp-fbscroller,
.cbp-fbscroller section {
  height: 100%;
  margin: 0;
  padding: 0;
}

/* 2. 固定導航:右側垂直居中 */
.cbp-fbscroller > nav {
  position: fixed;
  z-index: 9999;
  right: 50px;
  top: 50%;
  transform: translateY(-50%);
}
.cbp-fbscroller > nav a {
  display: block;
  width: 24px; height: 24px;
  margin: 15px 0;
  border-radius: 50%;
  border: 4px solid #fff;
  background: transparent;
  transition: background 0.3s;
}
.cbp-fbscroller > nav a:hover { background: rgba(255,255,255,0.6); }
.cbp-fbscroller > nav a.cbp-fbcurrent { background: #fff; }

/* 3. Section 視差背景:關鍵在 background-attachment: fixed */
.cbp-fbscroller section {
  position: relative;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  background-attachment: fixed; /* 核心屬性 */
  /* 內容居中 */
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 2rem;
  text-shadow: 0 2px 4px rgba(0,0,0,0.5);
}

/* 4. 各 Section 背景圖 */
#fbsection1 { background-image: url(images/1.jpg); }
#fbsection2 { background-image: url(images/2.jpg); }
#fbsection3 { background-image: url(images/3.jpg); }
#fbsection4 { background-image: url(images/4.jpg); }
#fbsection5 { background-image: url(images/5.jpg); }

/* 5. 內容區域半透明背景增強可讀性 */
.content {
  background: rgba(0,0,0,0.4);
  padding: 2rem 4rem;
  border-radius: 8px;
}

JavaScript 交互邏輯 (依賴 jQuery + jQuery Waypoints)

var cbpFixedScrollLayout = (function() {
  var config = {
    $sections: $('#cbp-fbscroller > section'),
    $navlinks: $('#cbp-fbscroller > nav:first > a'),
    currentLink: 0,
    $body: $('html, body'),
    animspeed: 650,
    animeasing: 'easeInOutExpo' // 需 jquery.easing 插件
  };

  function init() {
    // 1. 導航點擊平滑滾動
    config.$navlinks.on('click', function(e) {
      e.preventDefault();
      var idx = $(this).index();
      scrollAnim(config.$sections.eq(idx).offset().top);
    });

    // 2. Waypoints 監聽滾動更新導航高亮
    // 向下滾動:section 進入視口 30% 觸發
    config.$sections.waypoint(function(direction) {
      if (direction === 'down') changeNav($(this));
    }, { offset: '30%' });
    
    // 向上滾動:section 底部超出視口 30% 觸發
    config.$sections.waypoint(function(direction) {
      if (direction === 'up') changeNav($(this));
    }, { offset: '-30%' });

    // 3. 窗口 resize 時保持當前 section 置頂
    $(window).on('debouncedresize', function() {
      scrollAnim(config.$sections.eq(config.currentLink).offset().top);
    });
  }

  function changeNav($section) {
    config.$navlinks.eq(config.currentLink).removeClass('cbp-fbcurrent');
    config.currentLink = $section.index('section');
    config.$navlinks.eq(config.currentLink).addClass('cbp-fbcurrent');
  }

  function scrollAnim(top) {
    config.$body.stop().animate({ scrollTop: top }, config.animspeed, config.animeasing);
  }

  return { init: init };
})();

// 初始化
$(function() {
  cbpFixedScrollLayout.init();
});

依賴庫

  • jQuery
  • jQuery Waypoints (`waypoints.js`) - 滾動觸發檢測
  • jQuery Easing (`jquery.easing.js`) - 緩動函數 `easeInOutExpo`
  • Debounced Resize (`jquery.debouncedresize.js`) - resize 防抖

關鍵技術點

  1. background-attachment: fixed:背景相對視口固定,不隨容器滾動。這是純 CSS 視差的核心,無需 JS 計算位移,性能極佳。
  2. height: 100% 鏈:html/body/容器/section 都必須 100% 高度,否則 fixed 背景不會滿屏。
  3. Waypoints 双向檢測:向下/向上不同偏移量(30% / -30%),避免邊界閃爍,精準更新導航高亮。
  4. transform 居中導航:`top:50% + translateY(-50%)` 實現垂直居中,無需知道導航高度。

移動端兼容性警告

iOS Safari / Android Chrome 對 `background-attachment: fixed` 支持極差或有 Bug**(背景不固定、抖動、不顯示)。

解決方案:

  • 媒體查詢檢測移動端,改用 `background-attachment: scroll` + `transform: translateZ(0)` 強制 GPU 層,或放棄視差改為普通滾動。
  • 或使用 `background-attachment: fixed` 但將背景圖放在獨立固定層(`position:fixed; top:0; left:0; width:100%; height:100%; z-index:-1;`),JS 監聽滾動更新 `background-position-y`(模擬視差)。

結語

`background-attachment: fixed` 是實現視差滾動最簡單、性能最好的純 CSS 方案,桌面端體驗極佳。配合 Waypoints 做導航聯動,代碼量極小。移動端需優雅降級或改用 JS 模擬。

copyright © 萬盛學電腦網 all rights reserved