检测何时元素距窗口顶部小于100px,更改CSS [英] Detect when element is less than 100px from top of window, change CSS

查看:46
本文介绍了检测何时元素距窗口顶部小于100px,更改CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使div.projectsgrid为<距顶部100像素,jQuery将查看div.selectedwork是否具有CSS背景颜色#ffffff.如果没有,它将其背景色设置为#ffffff.一旦用户向上滚动并且div.projectsgrid从顶部超过100px,jQuery将删除背景色.我有以下代码无法正常工作:

I'm trying to make it so that when div.projectsgrid is < 100px from the top, jQuery will see if div.selectedwork has css background-color #ffffff. If not, it will set its background-color to #ffffff. Once the user scrolls back up and div.projectsgrid is more than 100px from the top, jQuery will remove the background color. I have the following code, which isn't working:

$(window).scroll(function(e){ 
    var el = $('.selectedwork'); 
    var top = $('#projectsgrid').offset().top;

    if ($(top) < 100 && el.css('background-color') != '#ffffff'){
        $(el).css({'background-color': '#ffffff'});
    }
    if ($(top) > 100 && el.css('background-color') == '#ffffff'){
        $(el).css({'background-color': ''});
    }
});

推荐答案

我将使用一个类而不是查看背景颜色.另外,您的"projectgrid"是一个ID,而不是一个类.我也将距离调整为200,因为看起来更好.

I would use a class instead of looking at the background color. Also, your "projectgrid" is an ID and not a class. I also adjusted the distance to 200, as it seemed to look better.

这就是我要做的:

CSS

.bg-black { background-color: #000; }

脚本

$(document).scroll(function(){
    var el = $('.selectedwork'),
        top = $('#projectsgrid').offset().top - $(document).scrollTop();
    if (top < 200 && !el.is('.bg-black')){
        $(el).addClass('bg-black');
    }
    if (top > 200 && el.is('.bg-black')){
        $(el).removeClass('bg-black');
    }  
});

这篇关于检测何时元素距窗口顶部小于100px,更改CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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