let stars = document.getElementById('stars') let moon = document.getElementById('moon') let mountains_behind = document.getElementById('mountains_behind') let text = document.getElementById('text') let btn = document.getElementById('btn') let mountains_front = document.getElementById('mountains_front') let header = document.querySelector('header')
window.addEventListener('scroll', function(){ let value = window.scrollY; stars.style.left = value * 0.25 + 'px' moon.style.top = value * 1.05 + 'px' mountains_behind.style.top = value * 0.5 + 'px' mountains_front.style.top = value * 0 + 'px' text.style.marginRight = value * 4 + 'px' text.style.marginTop = value * 1.5 + 'px' btn.style.marginTop = value * 1.5 + 'px' header.style.top = value * 0.5 + 'px' })
这段 JavaScript 代码实现了视差滚动效果。具体来说:
let 关键字声明了一些变量,如 stars、moon、mountains_behind 等等,使用 document.getElementById() 方法获取了每个元素的引用。