簡體   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