如何使用jQuery使固定定位的div随内容水平滚动?

31

我有一个带以下CSS的div.scroll_fixed:

.scroll_fixed {
    position:absolute
    top:210px

}
.scroll_fixed.fixed {
    position:fixed;
    top:0;
} 
我正在使用以下jQuery代码,在div到达页面顶部时设置.fixed类。
var top = $('.scroll_fixed').offset().top - parseFloat($('.scroll_fixed').css('margin-top').replace(/auto/, 0));

$(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= top) {
        // if so, ad the fixed class
        $('.scroll_fixed').addClass('fixed');
    } else {
        // otherwise remove it
        $('.scroll_fixed').removeClass('fixed');
    }
});

在解决垂直滚动条固定的问题方面,这很有效。但是在浏览器窗口较小时,水平滚动会导致此固定div右侧内容的冲突。

我希望div可以随着内容水平滚动。

请问有谁能给我指点一下方向?我对JS / JQuery还不熟悉。

基本上,我希望它像这个示例中的第二个方框那样工作。

3个回答

23

此演示保持了元素的 position:fixed 属性,并操作元素的 left 属性:

var leftInit = $(".scroll_fixed").offset().left;
var top = $('.scroll_fixed').offset().top - parseFloat($('.scroll_fixed').css('margin-top').replace(/auto/, 0));


$(window).scroll(function(event) {
    var x = 0 - $(this).scrollLeft();
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= top) {
        // if so, ad the fixed class
        $('.scroll_fixed').addClass('fixed');
    } else {
        // otherwise remove it
        $('.scroll_fixed').removeClass('fixed');
    }

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

});

使用leftInit函数时会考虑可能存在的左边距。在这里试一下: http://jsfiddle.net/F7Bme/


谢谢,这基本上就是我想要的功能。不幸的是,我的 div 嵌套在一个固定宽度的居中容器中。一旦 .fixed 类生效,布局就会变得混乱。固定的 div 不再跟随窗口调整大小时居中布局的移动。不确定我能否解决这个问题。请查看我的回复 http://jsfiddle.net/35nyK/2/。当您首次加载并尝试调整大小时,红色框会正确移动。一旦滚动并尝试调整大小,布局就会变得混乱。有没有办法相对于那个居中容器来处理定位? - jfeust
@jfeust:有趣,我会试着玩一下看看能得出什么。 - Andrew Whitaker
了不起,非常感谢。 - Sruit A.Suk

21

如果你还在寻找横向滚动的固定元素解决方案,以下内容或许会对其他人有所帮助。这个 jQuery 插件是专门为解决这个问题而创造的。

本演示展示了一个购物车汇总功能,即使将其固定到页面顶部,仍可水平滚动;此外,我还将其用于表格数据上方的标题:

演示: http://jsfiddle.net/y3qV5/434/ (已更新)

插件及源码:https://github.com/bigspotteddog/ScrollToFixed

使用方法:

$(document).ready(function() {
    $('#cart').scrollToFixed( { marginTop: 10 } );
});

Jsfiddle在Chrome 29.0.1547.66上完美无缺地运行,所以我想Chrome中的故障已经被修复了。 - Dejv

8

3
截至今天,即使在最新的Google Chrome浏览器中,粘性演示仍然无法正常工作,因此它似乎不再是有用的答案。链接不错,但我投票为-1。 - xmojmr
position: sticky; 是一个干净的解决方案。还有一些很好的 polyfill 可以让它在 Chrome 中工作。 - Duvrai
2018年:position: sticky的效果非常好,而且得到了很好的支持,除非你想在<thead><tr>中使用它。 - David
现场演示已经不再提供,根据文章描述,它只展示了垂直滚动。问题明确要求水平滚动,这似乎在使用“position: sticky”时有些棘手。 - carandraug

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接