ホームページ  >  記事  >  ウェブフロントエンド  >  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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。