在滚动上更改div的背景颜色 [英] Changing background color of div on scroll

查看:138
本文介绍了在滚动上更改div的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://jsfiddle.net/ncuydr9y/

BG颜色在启动时应为#1A1A1A,然后在滚动210像素后更改。不知道我哪里出错了。

BG color should be #1A1A1A on start then change after scrolling 210 px. Not sure where I'm going wrong.

$(document).ready(function(){       
        var scroll_pos = 0;
        $(document).scroll(function() { 
            scroll_pos = $(this).scrollTop();
            if(scroll_pos > 210) {
                $("#left-panel").css('background-color', '#1A1A1A');
            } else {
                $("#left-panel").css('background-color', 'red');
            }
        });
    });


推荐答案

您需要将滚动事件绑定到 div id =left-panel,因为那是带有滚动条的元素(即带<的元素code> overflow:auto 并且子元素大于它自己。)

You need to bind your scroll event to your div with id="left-panel", because that's the element that has the scrollbar on it (i.e. the element with overflow: auto and a child element larger than itself).

绑定到文档窗口将无效,因为在这种情况下,它们不是带滚动条的元素。

Binding to document or window won't work, because in this case they are not the element with the scrollbar.

工作现场演示:

$(document).ready(function () {
    var scroll_pos = 0;
    $("#left-panel").scroll(function () {
        scroll_pos = $(this).scrollTop();
        if (scroll_pos > 210) {
            $("#left-panel").css('background-color', '#1A1A1A');
        } else {
            $("#left-panel").css('background-color', 'red');
        }
        console.log(scroll_pos);
    });
});

#left-panel {
    position: fixed;
    top: 0;
    left: 0;
    width: 80%;
    height: 100%;
    z-index: 2;
    overflow:auto;
    height:2000px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="left-panel">
    <div style="height:5000px;">CONTENT</div>
</div>

JSFiddle版本: http://jsfiddle.net/ncuydr9y/1/

JSFiddle Version: http://jsfiddle.net/ncuydr9y/1/

这篇关于在滚动上更改div的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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