CSS如何在不使用jquery的情况下修复滚动后的元素位置

CSS How to fix element position after some scroll without using jquery

本文关键字:情况下 位置 元素 滚动 jquery CSS      更新时间:2023-09-26

我希望我的网站侧边栏的一个元素在滚动后得到修复。我正在搜索的功能与9gag网站在这里使用的功能相同:http://9gag.com/gag/abq3PbX?ref=fsidebar(特别是当你从某个点向下滚动页面时固定的最后一个方形广告)。如果不使用jquery或其他外部库,而只使用css/javascript,我怎么能做到这一点?

我已经完成了关于文档主体scrollTop的"fixed"answers"absolute"之间的切换。

function scrollFunction() {
    var scrollPos = document.body.scrollTop;
    if (scrollPos > 40) {
        document.getElementById("fixed-floater").style.position = "fixed";
        document.getElementById("fixed-floater").style.top = "0px";
    } else {
        document.getElementById("fixed-floater").style.position = "absolute";
        document.getElementById("fixed-floater").style.top = "40px";
    }
}
window.onscroll = scrollFunction;

http://jsfiddle.net/ua4fhrzy/1/

但您可能会考虑研究"粘性css"