gpt4 book ai didi

javascript - 将背景颜色链接到滚动位置

转载 作者:太空宇宙 更新时间:2023-11-04 07:12:41 24 4
gpt4 key购买 nike

我想将 body 元素的背景颜色链接到滚动位置,这样当页面一直滚动到顶部时,它的颜色为 1,但是当它滚动超过 screen.height 时,它完全不同的颜色,但我希望它被插值,这样当它滚动到一半时,颜色只过渡到一半。到目前为止,我已将其链接到

$(window).scrollTop() > screen.height 

$(window).scrollTop() < screen.height 

添加和删除一个改变背景颜色的类,但我希望它依赖于滚动位置,而不仅仅是触发事件,而是平滑地为其设置动画,因此快速滚动过渡得很快,慢速滚动过渡得慢。

最佳答案

一种可能的解决方案是将 rgb 颜色绑定(bind)到当前高度,计算步长并根据当前滚动位置设置新的 rgb 颜色。在这里,我创建了最简单的案例 - 黑白过渡:

const step = 255 / $('#wrapper').height();
const multiplier = Math.round(
$('#wrapper').height() /
$('#wrapper').parent().height()
);

$('body').scroll(() => {
const currentStyle = $('body').css('backgroundColor');
const rgbValues = currentStyle.substring(
currentStyle.lastIndexOf("(") + 1,
currentStyle.lastIndexOf(")")
);
const scrolled = $('body').scrollTop();
const newValue = step * scrolled * multiplier;
$('#wrapper').css('background-color', `rgb(${newValue}, ${newValue}, ${newValue})`);
});
html,
body {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
overflow-x: hidden;
background-color: rgb(0, 0, 0);
}

#wrapper {
height: 200%;
width: 100%;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<section id="wrapper"></section>

这是另一个从黄色过渡到蓝色的例子:

const step = 255 / $('#wrapper').height();
const multiplier = Math.round(
$('#wrapper').height() /
$('#wrapper').parent().height()
);

$('body').scroll(() => {
const currentStyle = $('body').css('backgroundColor');
const rgbValues = currentStyle.substring(
currentStyle.lastIndexOf("(") + 1,
currentStyle.lastIndexOf(")")
);
const scrolled = $('body').scrollTop();
const newValue = step * scrolled * multiplier;
$('#wrapper').css('background-color', `rgb(${255 - newValue}, ${255 - newValue}, ${newValue})`);
});
html,
body {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
overflow-x: hidden;
background-color: rgb(255, 255, 0);
}

#wrapper {
height: 200%;
width: 100%;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<section id="wrapper"></section>

关于javascript - 将背景颜色链接到滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51032952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com