用JS固定背景位置很不稳定

问题描述 投票:0回答:1

我在 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 代替,但没有任何改变。

javascript html css frontend web-frontend
1个回答
0
投票

无需使用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

© www.soinside.com 2019 - 2024. All rights reserved.