使 html 元素在滚动过去时保持原位

Make html element stay in place when scrolled past

本文关键字:过去时 滚动 html 元素      更新时间:2023-09-26

如何使html元素在滚动到之前不会固定?因此,当用户滚动时,它将处于正常位置,但是在用户滚动过去后它不会离开屏幕吗?

将侦听器附加到 onscroll 事件,如果scrollTop大于元素的 Y 位置,则将其设置为 position: fixed

我以前用过这段代码:

http://www.webdeveloperjuice.com/2011/08/07/how-to-fix-element-position-after-some-scroll-using-jquery/

(function($){
        $.fn.scrollFixed = function(params){
        params = $.extend( {appearAfterDiv: 0, hideBeforeDiv: 0}, params);
        var element = $(this);
        if(params.appearAfterDiv)
            var distanceTop = element.offset().top + $(params.appearAfterDiv).outerHeight(true) + element.outerHeight(true);
        else
            var distanceTop = element.offset().top;
        if(params.hideBeforeDiv)
            var bottom = $(params.hideBeforeDiv).offset().top - element.outerHeight(true) - 10;
        else
            var bottom = 200000;                
            $(window).scroll(function(){    
                if( $(window).scrollTop() > distanceTop && $(window).scrollTop() < bottom )         
                    element.css({'position':'fixed', 'top':'5px'});
                else
                    element.css({'position':'static'});             
            });           
        };
    })(jQuery);

然后只需调用元素:

$(document).ready( function(){
$("#scrollingDiv").scrollFixed({appearAfterDiv:'.sidebar p', hideBeforeDiv:'.footer'});
$("#scrollingDiv1").scrollFixed({hideBeforeDiv:'.footer'});
});

看看 jQuery Scrollfollow 插件。我已经使用它来方便地实现这种效果。

您只需在要保留在视图中的元素上调用它:

<script type="text/javascript">
        $( '#example' ).scrollFollow();
</script>

可以配置缓动、位置和其他参数。