简体   繁体   English

如何在JavaScript页面加载中执行背景位置

[英]How do I execute background-position on a JavaScript page load

I´m trying to position the background with background-position: center center; 我正在尝试使用background-position: center center; but when you start scrolling and the javascript is activated, it gets the wrong positioning. 但是当您开始滚动并激活javascript时,它将获得错误的位置。 Anyone have any suggestion? 有人有什么建议吗?

Check out the demo here: https://www.w3schools.com/code/tryit.asp?filename=G23Z0H5YSQCO 在此处查看演示: https : //www.w3schools.com/code/tryit.asp?filename=G23Z0H5YSQCO

Try this line to keep the horizontal centring and only change the y-position while scrolling: 尝试使用此行以保持水平居中,并仅在滚动时更改y位置:

document.getElementById("myDiv").style.backgroundPosition = "center " + (-window.pageYOffset / speed) + "px";

So your example should then look like this: 因此,您的示例应如下所示:

 <!DOCTYPE html> <html> <head> <style> #myDiv { background-image: url('https://dummyimage.com/1200x400/000/fff'); background-repeat: repeat; background-size:cover; background-position:center center; padding:20% 0; text-align:center; width:100%; } body {height:1400px;} </style> </head> <body> <script> document.addEventListener("DOMContentLoaded", function() { window.onscroll = function() { var speed = 8; document.getElementById("myDiv").style.backgroundPosition = "center " + (-window.pageYOffset / speed) + "px"; } }); </script> <div id="myDiv"> <h1>Headline</h1> <p>Lorem ipsum dolor sit amet</p> <button>Call to action</button> </div> </body> </html> 

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

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