繁体   English   中英

脚本标签在我的 index.html 中不起作用

[英]script tag in doesnt work in my index.html

index.html 中的脚本标签不起作用。 我不知道为什么它不起作用。 我也试过将它添加到另一个文件中并给它一个链接

 let stars = document.getElementById('stars') let moon = document.getElementById('moon') let mountain_behind = document.getElementById('mountain-behind') let mountain_front = document.getElementById('mountain-front') let btn = document.getElementById('btn') let text = document.getElementById('text') //let header = document.querySelector('header') window.addEventListener("scroll", function() { let value = window.screenY; stars.style.left = value * 0.25 + 'px' moon.style.top = value * 1.05 + 'px' mountain_behind.style.top = value * 0.5 + 'px' mountain_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" })
 body, html { height: 1000px; }
 <section> <img src="img/stars.png" id="stars"> <img src="img/moon.png" id="moon"> <img src="img/mountains_behind.png" id="mountain-behind"> <h2 id="text">Genesis 2k22</h2> <a href="#sec" id="btn" class="btn">Register Now</a> <img src="img/mountains_front.png" id="mountain-front"> </section>

问题是因为您检索垂直滚动 position 的逻辑有缺陷。 您需要从 offset 和clientY计算它:

 let stars = document.getElementById('stars') let moon = document.getElementById('moon') let mountain_behind = document.getElementById('mountain-behind') let mountain_front = document.getElementById('mountain-front') let btn = document.getElementById('btn') let text = document.getElementById('text') //let header = document.querySelector('header') window.addEventListener("scroll", function() { var doc = document.documentElement; var value = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); stars.style.left = value * 0.25 + 'px' moon.style.top = value * 1.05 + 'px' mountain_behind.style.top = value * 0.5 + 'px' mountain_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" })
 body, html { height: 1000px; }
 <section> <img src="img/stars.png" id="stars"> <img src="img/moon.png" id="moon"> <img src="img/mountains_behind.png" id="mountain-behind"> <h2 id="text">Genesis 2k22</h2> <a href="#sec" id="btn" class="btn">Register Now</a> <img src="img/mountains_front.png" id="mountain-front"> </section>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM