HTML CSS仅在正文到达特定点时才修复元素

HTML CSS fixed element only when body reaches a particular point

本文关键字:元素 CSS 正文 HTML      更新时间:2023-09-26

不确定该方法是什么或它是如何实现的。但我有兴趣了解它,以便在即将到来的项目中使用它。我指的是当块元素位于特定的 X/Y 轴上时,它似乎不再像固定位置元素一样工作,否则该元素充当固定位置元素。

我最常在导航中看到这种情况,其中页眉和页脚很大,当元素到达页眉底部或页脚顶部时,元素将停止充当固定元素

你可以做这样的事情,

$(window).scroll(function(){    
    if ($(this).scrollTop() > 250){ 
        $('#top').css('position','fixed'); 
    }
    else{
        $('#top').css('position','static');
    }
});

更好的方法是,

$(window).scroll(function(){    
    var top =  $('#top'); 
    if ($(this).scrollTop() > 250){
        if(top.css('position') !== 'fixed'){ 
            top.css('position','fixed'); 
        }
    }
    else{
        if(top.css('position') !== 'static'){
            top.css('position','static');
        }
    }
});

有一些插件可以为您执行此操作; 这是我以前使用过的一个:相对成功的链接。也有很好的例子。

如果你想自己做,这并不难。这个概念有点复杂;如果您将某些内容position更改为 fixed ,那么它不会像static那样占用空间。

当我遇到这个问题时,我在同一位置创建了第二个项目(或不创建,取决于您希望它出现的位置),这是不可见的。然后实现一个加载/滚动事件,该事件检查窗口的scrollTop是否大于非固定对象的top坐标。如果是,则显示固定对象。

像这样:

$("#yourObject").each(function() { // The ID should be the FIXED object.
    var $me = $(this);
    var $heightRival = $("#anotherObject"); // This ID should be the non-fixed object.
    $me.hide(); // Hide your fixed div.
    $(window).bind("load scroll",function() {
        var offset = $heightRival.offset(); // Get the document offset of the base object.
        var height = $heightRival.outerHeight(); // Get the height of the base object.
        if ($(window).scrollTop() > offset.top+height)
            $target.show(); // Can be a fade in, slide in, whatever.
        else
            $target.hide(); // Can be a fade out, etc.
    });
});

这只是一个基本的代码,但它应该让你走上正确的轨道。

看看这个插件,或者其他类似的插件:http://www.orangecoat.com/stickyscroll