【问题标题】:Link Background Color to Scroll Position将背景颜色链接到滚动位置
【发布时间】:2018-06-25 23:19:31
【问题描述】:
我想将 body 元素的背景颜色链接到滚动位置,这样当页面一直滚动到顶部时,它的颜色为 1,但是当它滚动过去 screen.height 时,它完全是不同的颜色,但我希望对它进行插值,以便在中途滚动时,颜色仅在中途过渡。到目前为止,我已将其链接到
$(window).scrollTop() > screen.height
和
$(window).scrollTop() < screen.height
添加和删除一个更改背景颜色的类,但我希望它依赖于滚动位置,而不仅仅是触发事件,而是平滑地为其设置动画,以便快速滚动过渡,慢速滚动过渡缓慢。
【问题讨论】:
标签:
javascript
jquery
html
css
【解决方案1】:
一种可能的解决方案是将 rgb 颜色绑定到当前高度,计算步长并根据当前滚动位置设置新的 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>
【解决方案2】:
var randomHex = function () {
return (parseInt(Math.random()*16)).toString(16) || '0';
};
var randomColor = function () {
return '#'+randomHex()+randomHex()+randomHex();
};
var randomGradient = function () {
$('.longContent').css('background', 'linear-gradient(0.5turn, #222, '+randomColor()+','+randomColor()+')');
};
$(window).on('load', randomGradient);
body {
margin: 0;
}
.longContent {
height: 400vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/17.2.0/Tween.min.js"></script>
<div class="longContent"></div>
【解决方案3】:
简单得多的方法是使用渐变作为背景来完成您想要做的事情。
这里对任何 JS 的需求绝对为零,只会减慢页面速度。
body {
height: 600vh;
background: linear-gradient(#2E0854, #EE3B3B)
}
你想用 JS 做这件事有什么特别的原因吗?