[英]Changing background color on scroll with javascript
https://codepen.io/tobiasthaden/pen/OVWKjm
$(window).scroll(function() {
$('section').each(function(i) {
if ($(this).position().top <= $(window).scrollTop()) {
$('body').css('background-color', $(this).attr('data-color'));
}
});
});
希望使用常規的舊 javascript 來復制這種效果。 我不想使用 jQuery!
有小費嗎?
const sections = document.querySelectorAll('section') window.addEventListener('scroll', function() { sections.forEach(section => { const distFromTop = document.body.scrollTop + section.getBoundingClientRect().top if (distFromTop < 10) { document.body.style.background = section.dataset.color } }) })
body { transition: background-color.2s ease; } section { height: 100vh; }
<section data-color="white"></section> <section data-color="green"></section> <section data-color="purple"></section> <section data-color="yellow"></section> <section data-color="blue"></section> <section data-color="white"></section>
這似乎工作得很好!
我會這樣做的。
const sections = document.querySelectorAll('section') document.addEventListener('scroll', () => { sections.forEach(section => { if(section.getBoundingClientRect().top <= document.body.scrollTop) { document.body.style.background = section.dataset.color } }) })
body { transition: background-color.2s ease; } section { height: 100vh; }
<section data-color="white"></section> <section data-color="green"></section> <section data-color="purple"></section> <section data-color="yellow"></section> <section data-color="blue"></section> <section data-color="white"></section>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.