js:根据滚动位置更改样式 [英] js: change style based in scroll position

查看:671
本文介绍了js:根据滚动位置更改样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可以更改元素的背景颜色(效果很好)

I have this code to change the background color of an element (which works fine)

<script>
window.onscroll = function() {
    if(document.body.scrollTop == 0) {
       jQuery("header#main-header").css('background-color', 'red');
    }
}
</script>

问题是,仅当页面滚动在0到100之间时,我才需要将颜色设置为红色;如果大于100,则需要将颜色设置为黄色.

Problem is that I need to set the color to red only if the page scroll is between 0 and 100 and set the color to yellow if is bigger than 100.

我在此页面中尝试过此操作: http://temporal-1.d246.dinaserver.com /,但不起作用:

I tried this in this page: http://temporal-1.d246.dinaserver.com/ but not working:

<script>
window.onscroll = function() {
    if(document.body.scrollTop <= 99) {
       jQuery("header#main-header").css('background-color', 'red');
    }
    if(document.body.scrollTop >= 100) {
       jQuery("header#main-header").css('background-color', 'yellow');
    }
}
</script>

推荐答案

好吧,您需要以不同的方式计算top偏移量

Well you need to calculate top offset a little differently

window.onscroll = function() {
    var doc = document.documentElement;
    var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
    if(top <= 99) {
       jQuery("header#main-header").css('background-color', 'red');
    }
    else {
       jQuery("header#main-header").css('background-color', 'yellow');
    }
} 

这篇关于js:根据滚动位置更改样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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