首頁  >  文章  >  web前端  >  如何使用 jQuery 使固定位置的 Div 與內容一起水平滾動?

如何使用 jQuery 使固定位置的 Div 與內容一起水平滾動?

DDD
DDD原創
2024-10-28 04:35:30144瀏覽

How to Make a Fixed-Position Div Scroll Horizontally with Content Using jQuery?

如何使用 jQuery 讓固定位置的 div 與內容水平滾動

為了確保固定的 div 與內容水平滾動,需要 CSS 和 jQuery 程式碼的組合。以下是如何實現它:

CSS

<code class="css">.scroll_fixed {
    position: absolute;
    top: 210px;
}

.scroll_fixed.fixed {
    position: fixed;
    top: 0;
}</code>

jQuery

<code class="javascript">// Retrieve the initial left offset
var leftInit = $(".scroll_fixed").offset().left;

// Get the top offset of the div
var top = $('.scroll_fixed').offset().top - parseFloat($('.scroll_fixed').css('margin-top').replace(/auto/, 0));


$(window).scroll(function(event) {
    // Calculate the horizontal scroll position
    var x = 0 - $(this).scrollLeft();

    // Calculate the vertical scroll position
    var y = $(this).scrollTop();

    // Position the div based on scroll
    // Horizontally: Left margin of the initial position minus the horizontal scroll position
    // Vertically: Top margin of the initial position minus the vertical scroll position
    if (y >= top) {
        // Display the div at the top of the viewport
        $('.scroll_fixed').addClass('fixed');
    } else {
        // Remove the 'fixed' class from the div
        $('.scroll_fixed').removeClass('fixed');
    }

    $(".scroll_fixed").offset({
        left: x + leftInit,
        top: y
    });

});</code>

此程式碼透過調整div 的left 屬性來管理水平同步。 leftInit 變數合併了可能的左邊距,以提高函數的準確性。

以上是如何使用 jQuery 使固定位置的 Div 與內容一起水平滾動?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn