」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何實現錨鏈接平滑滾動?

如何實現錨鏈接平滑滾動?

發佈於2024-12-21
瀏覽:139

How Can I Achieve Smooth Scrolling with Anchor Links?

在點擊錨連結時平滑滾動

使用錨連結導航網頁時,使用者期望無縫過渡到目標部分。然而,預設的滾動行為可能會很突然。本文探討了在點擊錨連結時實現平滑滾動的技術。

本機支援

Chrome 和 Firefox 等瀏覽器引入了對平滑滾動的本機支援。這是透過捲動到視圖時使用值為「smooth」的「behavior」屬性來實現的:

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

jQuery 外掛程式

對於較舊的瀏覽器,jQuery 外掛程式可以平滑捲動動畫。此技術使用「animate」方法將頁面移至目標部分:

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});

增強技術

如果目標元素缺少ID,可以使用以下修改後的jQuery 插件:

$('a[href^="#"]').click(function () {
    $('html, body').animate({
        scrollTop: $('[name="'   $.attr(this, 'href').substr(1)   '"]').offset().top
    }, 500);

    return false;
});

效能最佳化

在變數中快取「$('html, body')」選擇器可增強效能:

var $root = $('html, body');

$('a[href^="#"]').click(function () {
    $root.animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);

    return false;
});

保留URL 哈希

要在平滑滾動時更新URL 哈希,請使用“animate”回調:

var $root = $('html, body');

$('a[href^="#"]').click(function() {
    var href = $.attr(this, 'href');

    $root.animate({
        scrollTop: $(href).offset().top
    }, 500, function () {
        window.location.hash = href;
    });

    return false;
});

透過實施其中一項技術,您可以在使用錨定連結導航頁面時提供精美且使用者友好的滾動體驗。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3