萬盛學電腦網

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

JavaScript 實現左右彈性滾動對聯廣告:從左/右側飛入、跟隨滾動、關閉功能完整實現

效果拆解

「對聯廣告」= 固定在視窗左右兩側、隨頁面滾動平滑跟隨、可選擇性從屏外飛入、提供關閉按鈕。核心技術點:

  • `position: fixed` 相對視窗定位
  • 滾動事件中計算目標位置,緩動動畫(原文用 `setInterval` + 線性插值)
  • 現代寫法:`requestAnimationFrame` + CSS `transition` 或 Web Animations API

現代重構版(ES6 類、rAF、CSS 過渡)

class CoupletAd {
  constructor(options = {}) {
    this.leftHTML = options.leftHTML || '';
    this.rightHTML = options.rightHTML || '';
    this.distance = options.distance || 80; // 距離視窗邊緣
    this.top = options.top || 100;          // 距離頂部
    this.duration = options.duration || 800; // 飛入動畫時長
    this.easing = options.easing || 'ease-out';
    this.zIndex = options.zIndex || 9999;
    this._init();
  }
  
  _init() {
    // 創建左右兩個容器
    this.leftEl = this._createAd('couplet-left', this.leftHTML, { left: this.distance });
    this.rightEl = this._createAd('couplet-right', this.rightHTML, { right: this.distance });
    
    document.body.appendChild(this.leftEl);
    document.body.appendChild(this.rightEl);
    
    // 初始隱藏在屏外(飛入前)
    this.leftEl.style.transform = 'translateX(-150%)';
    this.rightEl.style.transform = 'translateX(150%)';
    
    // 啟用 CSS 過渡
    requestAnimationFrame(() => {
      this.leftEl.style.transition = `transform ${this.duration}ms ${this.easing}`;
      this.rightEl.style.transition = `transform ${this.duration}ms ${this.easing}`;
      this.leftEl.style.transform = 'translateX(0)';
      this.rightEl.style.transform = 'translateX(0)';
    });
    
    // 滾動跟隨:fixed 定位已自動跟隨,無需 JS 計算
    // 若需「彈性」跟隨(延遲跟隨),見下方進階版
  }
  
  _createAd(id, html, position) {
    const el = document.createElement('div');
    el.id = id;
    el.className = 'couplet-ad';
    el.style.cssText = `
      position: fixed;
      top: ${this.top}px;
      z-index: ${this.zIndex};
      ${position.left ? `left: ${position.left}px;` : `right: ${position.right}px;`}
      pointer-events: auto;
    `;
    el.innerHTML = html;
    
    // 添加關閉按鈕
    const closeBtn = document.createElement('button');
    closeBtn.className = 'couplet-close';
    closeBtn.innerHTML = '×';
    closeBtn.setAttribute('aria-label', '關閉廣告');
    closeBtn.onclick = () => this.close();
    el.appendChild(closeBtn);
    
    return el;
  }
  
  close() {
    this.leftEl.style.transition = `transform ${this.duration}ms ease-in`;
    this.rightEl.style.transition = `transform ${this.duration}ms ease-in`;
    this.leftEl.style.transform = 'translateX(-150%)';
    this.rightEl.style.transform = 'translateX(150%)';
    setTimeout(() => {
      this.leftEl.remove();
      this.rightEl.remove();
    }, this.duration);
  }
  
  // 靜態工廠方法
  static create(options) {
    return new CoupletAd(options);
  }
}

// 使用
CoupletAd.create({
  leftHTML: '左側廣告',
  rightHTML: '右側廣告',
  top: 150,
  distance: 20
});

CSS 樣式建議

.couplet-ad {
  /* 確保內容不超出 */
  overflow: hidden;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.couplet-close {
  position: absolute;
  top: -12px;
  right: -12px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #fff;
  border: 1px solid #ddd;
  font-size: 16px;
  line-height: 22px;
  text-align: center;
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(0,0,0,0.2);
  z-index: 10;
}
.couplet-close:hover { background: #f5f5f5; }

/* 彈性跟隨:如果不想用 fixed,改用 absolute + JS 計算 */
.couplet-ad.elastic {
  position: absolute; /* 相對文檔 */
  transition: top 0.3s ease-out;
}

進階:彈性跟隨(非 fixed,隨滾動延遲移動)

class ElasticCoupletAd extends CoupletAd {
  _init() {
    super._init();
    // 改為 absolute,需手動計算位置
    this.leftEl.style.position = 'absolute';
    this.rightEl.style.position = 'absolute';
    this.leftEl.style.left = `${this.distance}px`;
    this.rightEl.style.right = `${this.distance}px`;
    
    this._bindScroll();
  }
  
  _bindScroll() {
    let ticking = false;
    const update = () => {
      const scrollTop = window.scrollY || document.documentElement.scrollTop;
      const targetTop = scrollTop + this.top;
      
      // 緩動:當前位置 + (目標 - 當前) * 0.1
      this.leftEl.style.top = `${this.leftEl.offsetTop + (targetTop - this.leftEl.offsetTop) * 0.1}px`;
      this.rightEl.style.top = `${this.rightEl.offsetTop + (targetTop - this.rightEl.offsetTop) * 0.1}px`;
      
      ticking = false;
    };
    
    window.addEventListener('scroll', () => {
      if (!ticking) {
        requestAnimationFrame(update);
        ticking = true;
      }
    }, { passive: true });
  }
}

無障礙與 SEO 注意

  • 廣告圖片**必須有 `alt` 屬性**
  • 關閉按鈕需 `aria-label`、鍵盤可聚焦、Enter/Space 可觸發
  • 避免遮擋主要內容,`z-index` 不要過高(9999 通常足夠)
  • 考慮 `prefers-reduced-motion` 媒體查詢,減少動畫

結語

對聯廣告核心是 **`position: fixed` + CSS `transition` 實現飛入/跟隨**,現代瀏覽器無需 JS 計算位置。若需「彈性跟隨」效果,改用 `absolute` + `requestAnimationFrame` 緩動計算。務必提供關閉按鈕、遵循無障礙標準、避免干擾主內容閱讀。

copyright © 萬盛學電腦網 all rights reserved