我根据您的需要制作了一个基本示例,请看一下并告诉我是否理解您所说的。我在js代码中添加了一些额外的解释,小提琴在这篇文章的末尾。
基本的 HTML 标记
<heade id="webHeader">
<nav>
<ul>
<li><a href="#">Nav item 1</a></li>
<li><a href="#">Nav item 2</a></li>
<li><a href="#">Nav item 3</a></li>
</ul>
</nav>
</heade>
<section id="section-1" data-color="#330000"></section>
<section id="section-2" data-color="#00B200"></section>
<section id="section-3" data-color="#803380"></section>
我要使用 SCSS,但您可以轻松更新到基本 CSS(我假设粘性标题是默认情况下,所以我在正文中添加了一个与标题高度相同的填充)
$headerHeight: 100px;
body {
padding-top: $headerHeight;
}
#webHeader {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: $headerHeight;
background: #000F1F; /*default background color and fallback if there is no section available for it*/
nav {
padding: 40px;
float: right;
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #fff;
font-weight: 700;
text-decoration: none;
}
}
}
section {
width: 100%;
height: 500px;
background-color: grey;
border-bottom: 1px dashed #fff;
}
还有 jQuery 代码。
(function($){
// cache dom elements
var $header = $('#webHeader');
var $window = $(window);
var headerHeight = $header.outerHeight(true);
var colors = []; // add colors here
var sections = []; // add sections positions
$('section').each(function(){
var $this = $(this);
colors.push($this.data('color'));
sections.push($this.position().top);
});
// duplicate first color
colors.unshift(colors[0]);
$window.on('scroll', function(){
var position = $window.scrollTop() + headerHeight;
var index = inInterval(position, sections);
var distance = position - sections[index];
$header.attr('style', linearGradient( colors[index+1], colors[index], distance ) );
}).trigger('scroll');
// trigger scroll when the page is loaded to update the header color to the current position
})(jQuery);
// Treat array elements as intervals
function inInterval(value, array) {
// cache array length
var arrLen = array.length;
// Add one more value at the end of array to avoid having problems on last item
array.push(array[arrLen-1]*2);
for (var i = 0; i < arrLen+1; i++)
if (value >= array[i] && value <= array[i+1])
return i;
}
function linearGradient(start, end, distance) {
var distanceStart = distance + '%';
var distanceEnd = 100 - distance + '%';
return "background: -webkit-gradient(linear, left top, left bottom, color-stop(0, "+ start +"), color-stop("+ distanceStart +", "+ start +"), color-stop("+ distanceStart +", "+ end +"), color-stop(100, "+ end +")";
}
您可以在 fiddle 中看到它的工作原理。我会做一些更新,但我现在有点忙,但我建议您阅读更多关于 jQuery debounce 的信息并尝试smart scroll(用于调用更少的滚动事件 - 有利于性能)
我希望是你正在寻找的:)