萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

HTML5 背景彈性滾動導航:Magic Line 動畫底線追蹤當前頁籤

效果展示

導航列底部有一條彩色底線(Magic Line),當滑鼠懸停不同頁籤時,底線以彈性動畫平滑滑動至該頁籤位置,寬度自適應文字長度;移開滑鼠時彈回當前頁面頁籤。極大提升導航互動質感。

核心 HTML 結構

<nav id="nav-wrap">
    <ul id="example" class="group">
        <li class="current"><a href="#" rel="#ff6b6b">首頁</a></li>
        <li><a href="#" rel="#4ecdc4">關於我們</a></li>
        <li><a href="#" rel="#ffe66d">服務項目</a></li>
        <li><a href="#" rel="#95e1d3">作品集</a></li>
        <li><a href="#" rel="#f38181">聯絡我們</a></li>
    </ul>
</nav>

關鍵點:rel 屬性儲存各頁籤專屬底線顏色。

CSS 樣式(精簡核心)

#nav-wrap { 
    margin: 0 auto; 
    background: #2c3e50; 
    border-top: 3px solid #fff; 
    border-bottom: 3px solid #fff; 
}

#example { 
    width: 800px; margin: 0 auto; 
    list-style: none; position: relative; 
    display: flex; /* 現代佈局替代 float */
}

#example li { display: inline; } /* 或 flex item */

#example li a {
    position: relative; z-index: 200;
    color: #aaa; font: bold 16px/1 sans-serif;
    display: block; float: left; /* 保留 float 相容舊瀏覽器 */
    padding: 12px 20px 12px 30px;
    text-decoration: none; text-transform: uppercase;
    transition: color 0.3s ease;
}

#example li a:hover { color: #fff; }

/* Magic Line 底線 */
#magic-line {
    position: absolute; bottom: 0; left: 0; height: 4px;
    border-radius: 4px 4px 0 0;
    z-index: 100; /* 低於連結 z-index:200 */
    transition: all 0.4s cubic-bezier(0.68, -0.55, 0.27, 1.55); /* 彈性緩動 */
}

.current a { color: #fff !important; }

JavaScript 核心邏輯 (jQuery 版)

$(function() {
    const $mainNav = $('#example');
    const $magicLine = $('
  • ').appendTo($mainNav); // 初始化:對齊當前頁籤 const $current = $('.current a'); $magicLine .width($current.parent().width()) .height($mainNav.height()) .css('left', $current.position().left) .data('origLeft', $current.position().left) .data('origWidth', $magicLine.width()) .data('origColor', $current.attr('rel')); // 懸停動畫 $('#example li').find('a').hover(function() { const $el = $(this); const leftPos = $el.position().left; const newWidth = $el.parent().width(); const newColor = $el.attr('rel'); $magicLine.stop().animate({ left: leftPos, width: newWidth, backgroundColor: newColor }, 400, 'easeOutBack'); // 需 jQuery UI 或 easing 外掛 }, function() { $magicLine.stop().animate({ left: $magicLine.data('origLeft'), width: $magicLine.data('origWidth'), backgroundColor: $magicLine.data('origColor') }, 400, 'easeOutBack'); }); });

    原生 JS 現代重構版(無依賴、更輕量)

    <script>
    class MagicLineNav {
        constructor(navSelector) {
            this.nav = document.querySelector(navSelector);
            this.list = this.nav.querySelector('ul');
            this.items = [...this.list.querySelectorAll('li')];
            this.line = document.createElement('li');
            this.line.id = 'magic-line';
            this.list.appendChild(this.line);
            
            this.currentItem = this.list.querySelector('.current') || this.items[0];
            this.init();
            this.bindEvents();
        }
        
        init() {
            this.updateLine(this.currentItem, false); // 無動畫初始化
            this.line.style.transition = 'all 0.5s cubic-bezier(0.68, -0.55, 0.27, 1.55)';
        }
        
        bindEvents() {
            this.items.forEach(item => {
                const link = item.querySelector('a');
                item.addEventListener('mouseenter', () => this.updateLine(item, true));
                item.addEventListener('mouseleave', () => this.updateLine(this.currentItem, true));
                item.addEventListener('focusin', () => this.updateLine(item, true)); // 鍵盤支援
            });
            
            this.nav.addEventListener('mouseleave', () => 
                this.updateLine(this.currentItem, true)
            );
            
            // 點擊更新當前頁
            this.items.forEach(item => {
                item.querySelector('a').addEventListener('click', e => {
                    e.preventDefault(); // Demo 防止跳轉
                    this.setCurrent(item);
                });
            });
        }
        
        setCurrent(item) {
            this.items.forEach(i => i.classList.remove('current'));
            item.classList.add('current');
            this.currentItem = item;
            this.updateLine(item, false); // 即時更新無動畫
        }
        
        updateLine(item, animate = true) {
            const link = item.querySelector('a');
            const rect = link.getBoundingClientRect();
            const listRect = this.list.getBoundingClientRect();
            
            const left = rect.left - listRect.left;
            const width = rect.width;
            const color = link.dataset.color || link.getAttribute('rel') || '#fff';
            
            if (!animate) this.line.style.transition = 'none';
            else this.line.style.transition = 'all 0.5s cubic-bezier(0.68, -0.55, 0.27, 1.55)';
            
            this.line.style.left = left + 'px';
            this.line.style.width = width + 'px';
            this.line.style.backgroundColor = color;
            
            // 強制重繪確保無動畫生效
            if (!animate) this.line.offsetHeight; 
        }
    }
    
    // 初始化
    document.addEventListener('DOMContentLoaded', () => {
        new MagicLineNav('#nav-wrap');
    });
    </script>

    關鍵技術細節

    彈性緩動函數

    cubic-bezier(0.68, -0.55, 0.27, 1.55) 產生「超過目標再回彈」的彈簧感。可用 cubic-bezier.com 視覺化調整。

    position() vs offset()

    • position():相對 父元素 定位(需父元素 position: relative)
    • offset():相對 文件 定位
    • Magic Line 在 <ul> 內絕對定位,故用 position() 或 getBoundingClientRect() 相減

    色彩管理

    使用 data-color 或 rel 屬性儲存各頁籤專屬色,JS 讀取套用至 Magic Line。

    進階變化

    垂直導航版

    #example { flex-direction: column; width: 200px; }
    #magic-line { 
        width: 4px; height: auto; 
        top: 0; left: 0; 
        border-radius: 0 4px 4px 0; 
    }
    .updateLine() { /* 計算 top/height 而非 left/width */ }

    指示器形狀變化

    • 圓形指示器:width: height: 8px; border-radius: 50%; transform: translateX(-50%);
    • 三角形:width: 0; height: 0; border: 6px solid transparent; border-bottom-color: var(--color);
    • SVG 路徑動畫:<svg><path id="indicator" /></svg> 配合 stroke-dashoffset

    整合路由器

    // Vue Router / React Router 整合範例
    watch: {
        '$route.matched[0].path': function(to) {
            const item = this.items.find(i => i.path === to);
            if (item) this.magicLine.setCurrent(item.el);
        }
    }

    無障礙與效能檢查清單

    • [ ] 導航使用 <nav> + <ul> 語意結構
    • [ ] 當前頁面 aria-current="page"
    • [ ] 鍵盤 Tab 可聚焦每個連結,焦點樣式明顯
    • [ ] prefers-reduced-motion 媒體查詢停用動畫
    • [ ] 動畫使用 transform/opacity 避免佈局抖動
    • [ ] will-change: left, width, background-color 提示瀏覽器優化
    copyright © 萬盛學電腦網 all rights reserved