首页  >  文章  >  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