html 用JS固定背景的位置是不稳定的

3xiyfsfu  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(120)

我在JS中固定div的背景位置来创建视差效果(背景附件对我的目标不太好)。但有时候,它的工作原理是这样的:背景可能不会立即改变位置。
下面是一个例子:https://youtu.be/SshLhAfD3oY
CSS:

.box {
    width: 100%;
    height: 1000px;
    background-image: url("e4AAAgCw3OA-960.jpg");
    background-size: cover;
    background-position-y: var(--check);
}

JS:

function parallax() {
    document.body.style = `--check: ${window.pageYOffset}px`;
}

window.addEventListener('scroll', (e) => {
    parallax();
});

有什么想法吗?
我尝试使用 * window.scrollY * 代替,但没有任何变化。

kxkpmulp

kxkpmulp1#

不需要使用JavaScript。我建议在CSS中使用background-attachment: fixed
像这样修改你的CSS:

.box {
    width: 100%;
    height: 1000px;
    background-image: url("e4AAAgCw3OA-960.jpg");
    background-size: cover;
    background-attachment: fixed;
}

这是一个视差滚动效果的例子:

<!DOCTYPE html>
<html>
<head>
<style> 
.fixed-bg {
  background-image: url("img_tree.gif");
  min-height: 500px;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}
</style>
</head>
<body>

<p>In this example, we have created a fixed background image that will disappear slowly on scroll. Scroll the page to see the effect. <strong>Note:</strong> Try to remove the background-attachment property to really understand this example.</p>
 
<div class="fixed-bg"></div>

<div style="height:800px;background-color:yellow;">This div is only here to enable scrolling (height = 800 pixels).</div>

</body>
</html>

来源:https://www.w3schools.com/cssref/tryit.php?filename=trycss_background-attachment_fixed

相关问题