萬盛學電腦網

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

JavaScript 運動框架實戰:側邊欄滑入滑出動畫完整實作與優化

效果描述

固定寬度 319px 的側邊欄預藏於視窗左側 (left: -320px)。滑鼠移入滑出顯示 (left: 0),移出滑回隱藏。右側標籤 span 固定於側邊欄右緣,隨面板移動。

基礎版實作

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>側邊欄動畫</title>
<style>
  #div1 { width:319px; height:340px; border:1px solid #FFF; position:absolute; top:100px; left:-320px; background:url(images/1.png) no-repeat; }
  #div1 span { width:30px; height:130px; position:absolute; right:-23px; top:95px; background:red; color:#FFF; text-align:center; line-height:40px; border-radius:0 200px 200px 0; font-family:"微軟雅黑"; }
</style>
<script>
window.onload = function() {
  var oDiv = document.getElementById("div1");
  var time = null, speed = 8;

  oDiv.onmouseover = function() {
    clearInterval(time);
    time = setInterval(function() {
      if (oDiv.offsetLeft >= 0) { clearInterval(time); }
      else { oDiv.style.left = oDiv.offsetLeft + speed + 'px'; }
    }, 1);
  };

  oDiv.onmouseout = function() {
    clearInterval(time);
    time = setInterval(function() {
      if (oDiv.offsetLeft <= -320) { clearInterval(time); }
      else { oDiv.style.left = oDiv.offsetLeft - speed + 'px'; }
    }, 1);
  };
};
</script></head>
<body>
<div id="div1"><span>分享到</span></div>
</body></html>

優化版:統一移動函式,消除重複邏輯

<script>
window.onload = function() {
  var oDiv = document.getElementById("div1");
  var time = null, spe = 8, speed = null;

  function move(targetLeft) {
    clearInterval(time);
    time = setInterval(function() {
      if (oDiv.offsetLeft > targetLeft) speed = -spe;
      else speed = spe;
      if (oDiv.offsetLeft === targetLeft) { clearInterval(time); }
      else { oDiv.style.left = oDiv.offsetLeft + speed + 'px'; }
    }, 1);
  }

  oDiv.onmouseover = function() { move(0); };
  oDiv.onmouseout  = function() { move(-320); };
};
</script>

核心知識點

  1. 定時器管理:啟動前必須 clearInterval 防止多重疊加導致加速失控。
  2. 位置判斷:使用 offsetLeft 獲取當前位置,配合目標值控制方向與停止條件。
  3. 速度控制:固定像素步長 speed,簡單高效;進階可改用緩動函式 (ease-out) 提升手感。
  4. 事件綁定於容器:onmouseover/out 綁在整個 div1 上,包含標籤區域,避免滑鼠進入標籤觸發 mouseout 導致閃爍。

現代化改良方向

  • 改用 CSS transition: left 0.3s ease,JS 僅切換 class,效能更佳、程式碼極簡。
  • 使用 requestAnimationFrame 實現平滑幀動畫。
  • 封裝為可複用元件:new Sidebar({trigger: 'hover', direction: 'left', width: 320})。

此範例展示傳統 JS 定時器動畫的核心邏輯:位置插值、邊界檢測、定時器生命週期管理。理解這些基礎,有助於深入掌握現代動畫庫(如 GSAP、Anime.js)的底層原理。

copyright © 萬盛學電腦網 all rights reserved