我该如何模拟Position:Sticky?

问题描述 投票:0回答:2

如果您不知道位置:粘性,请观看这​​20秒长的视频:https://www.youtube.com/watch?v=jA67eda5i-A

此CSS功能在W3的讨论中,我相信是在壁虎中实现的。但这不是重点,重点是并不是所有的浏览器都支持它,我真的想要该功能。

有什么办法可以同时使用CSS和/或javascript和/或jquery来做到这一点吗?

javascript jquery html css sticky
2个回答
2
投票

这里有一个简单的jquery插件:: http://stickyjs.com/


0
投票

为了避免使用插件,我使用jquery 1.8+创建了以下javascript方法。

第一个参数是您要设置粘性的元素。第二个参数是optionnal,它是一个布尔值,通过设置300ms的较小超时来提高浏览器性能。

function simulateSticky(elt, timeout) {
    var move = function() {
        var scrollTop = $(window).scrollTop();
        var scrollBottom = $(document).height() - scrollTop - $(window).height();

        var eltTop = elt.parent().offset().top;
        var eltBottom = $(document).height() - eltTop -  elt.parent().outerHeight();

        if (scrollTop < eltTop) { // Top case
            elt.css({
                position: "absolute",
                width: "100%",
                top:"auto",
                right: "0px",
                bottom: "auto",
                left: "0px",
            });
        }
        else if (scrollTop >= eltTop && scrollBottom >= eltBottom) { // Middle case
            elt.css({
                position: "fixed",
                width: elt.parent().width(),
                top:"0px",
                right: "auto",
                bottom: "auto",
                left: "auto",
            });
        }
        else { // Bottom case
            elt.css({
                position: "absolute",
                width: "100%",
                top:"auto",
                right: "0px",
                bottom: "0px",
                left: "0px",
            });
        }
    };

    // Use of a timeout for better performance
    if (timeout) {
        var timeoutId;
        $(window).scroll(function() {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(function() {
                move();
            }, 300);
        });
    }
    else {
        $(window).scroll(move);
    }

    // Initial call
    move();
}
© www.soinside.com 2019 - 2024. All rights reserved.