How do I get a fixed position div to scroll horizontally with the content? Using jQuery

别说谁变了你拦得住时间么 提交于 2019-11-26 18:53:01

The demo is keeping the element's position:fixed and manipulating the left property of the element:

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
    });

});

Using leftInit takes a possible left margin into account. Try it out here: http://jsfiddle.net/F7Bme/

bigspotteddog

You have probably moved on by now, but here is an answer for anyone else looking for a horizontally scrollable fixed element solution. This jquery plugin was created to solve this exact problem.

This demo uses a shopping cart summary that will still scroll horizontally when fixed to the top of the page; and, I have also used it for a header above tabular data:

Demo: http://jsfiddle.net/y3qV5/434/ (updated)

Plugin and source: https://github.com/bigspotteddog/ScrollToFixed

Usage:

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

use css property position:sticky to get it.

Here is the article explained and live demo.

http://updates.html5rocks.com/2012/08/Stick-your-landings-position-sticky-lands-in-WebKit

the only drawback is browser compatibility.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!