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

时间:2019-03-14 20:40:34

标签: javascript

我正在尝试使用webSocketStompClient.messageConverter = new MappingJackson2MessageConverter() 定位背景,但是当您开始滚动并且激活javascript时,它的定位错误。有人有建议吗?

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

1 个答案:

答案 0 :(得分:0)

尝试使用此行以保持水平居中,并仅在滚动时更改y位置:

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

因此您的示例应如下所示:

<!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>