当滚动到位置时将 Div 位置设置为固定 - jQuery

Dan*_*ris 5 html jquery scroll position css-position

我正在使用一个右侧边栏,其中包含三个垂直对齐的滑块。我希望当我向下滚动到 200 像素时固定侧边栏的位置。到目前为止,这是我的代码:

$(document).ready(function() {
    window.onscroll = function() {
        if (window.pageYOffset >= 200){
            $('.col-right').css({position: 'fixed', right: '490px'});
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我使用这段代码时什么也没有发生。它检测到我正在滚动,但它没有将 CSS 属性设置为“col-right”类,即侧边栏。我这样做对吗?

Dan*_*ris 6

好吧,我明白了。我更改$jQuery并且一切正常。这是我的工作解决方案:

jQuery(document).ready(function(){
    window.onscroll = function() {
        if (window.pageYOffset >= 200){
            jQuery('.col-right').css({position: 'fixed', right: '490px', top: '40px'});
        }
        else {
            jQuery('.col-right').css({position: '', right: '', top: ''});
        }
    }
});
Run Code Online (Sandbox Code Playgroud)


ade*_*neo 5

代替:

.css({position: fixed, right: 490px});
Run Code Online (Sandbox Code Playgroud)

.css({position: 'fixed', right: '490px'});
Run Code Online (Sandbox Code Playgroud)

字符串应该加引号!