CSS如何在一些滚动后修复元素位置而不使用jquery [英] CSS How to fix element position after some scroll without using jquery

查看:120
本文介绍了CSS如何在一些滚动后修复元素位置而不使用jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的网站侧边栏的某个元素在滚动后进行修复。我要搜索的功能与9gag网站所使用的功能相同: http://9gag.com/ gag / abq3PbX?ref = fsidebar (特别是从某个点向下滚动页面时修复的最后一个方形广告)。我怎样才能做到这一点,而不使用jQuery或其他外部库,但只使用CSS / JavaScript?

我已经完成通过在'fixed'和'absolute'之间切换文档的body scrollTop。

  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/



但您可能会考虑查看sticky css


I want an element of my websites's sidebar to be fixed after some scrolling. The functionality i'm searching is the same used by 9gag website here: http://9gag.com/gag/abq3PbX?ref=fsidebar (specifically the last square ads that is fixed when you scroll down the page from some point). How can i do the same without using jquery or other external libraries, but using css/javascript only?

解决方案

I've done by switching between 'fixed' and 'absolute' regarding the document's body scrollTop.

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/

But you might consider looking into "sticky css"

这篇关于CSS如何在一些滚动后修复元素位置而不使用jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆