document.querySelector("body").onscroll = function() {
const main = document.querySelector("main");
const scrolltotop = document.scrollingElement.scrollTop;
const factor = 0.5; // <- this factor here is my problem
const yvalue = scrolltotop * factor;
const xvalue = "center";
main.style.backgroundPosition = xvalue + " " + yvalue + "px";
}
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
header {
height: 40%;
}
main {
width: 100%;
background-image: url("https://images.pexels.com/photos/30005397/pexels-photo-30005397/free-photo-of-colorful-macaws-perched-in-lush-cancun-jungle.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2");
/* <- This image is just an example */
background-repeat: no-repeat;
background-size: 100%;
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
}
main>* {
width: 25em;
height: 40em;
background: gray;
margin: 2%;
font-size: 150%;
align-content: center;
text-align: center;
color: blue;
}
<header>
<p>Header p content</p>
</header>
<main>
<p>Main element 1</p>
<p>Main element 2</p>
<p>Main element 3</p>
<p>Main element 4</p>
<p>Main element 5</p>
<p>Main element 6</p>
<p>Main element 7</p>
<p>Main element 8</p>
<p>Main element 9</p>
</main>
因此,我需要的是一个公式,该公式会自动计算该因子,无论您如何调整屏幕大小,无论标头,主或主元素的高度如何,该公式始终确保背景图像的底部与网站的底部完美匹配。如果您能帮助我,我真的很感激!
我决定分享我自己想出的答案,以防我之后的其他人有同样的问题,并希望在这里找到答案:
const main = document.queryselector(“ main”); 我这样做是因为我希望视频效应能够使用的背景图像适用于主要元素。
const buckdertheight = main.offsetWidth *(3.0/2.0);
我想出的公式总是将背景图像的底部与页面的底部对齐,这需要背景图像的高度。为此,我使用main.OffsetWidth(我设置了Main以占据页面的宽度的100%,因此这起作用)与背景图像的高度/宽度比相乘。在我以鹦鹉图像为例的情况下,是3/2。
ScreenHeight= Math.max(window.screen.availheight,window.innerheight);一个也需要屏幕的高度。问题是我不能使用一个值,因为有时会给我带来太小的结果。但是,使用window.screen.availheight或window的最大值。Innerheight似乎总是对我有用。
mainHeight= const mainheight = main.offsetheight;
需要您要应用视差效应的元素的高度。
const factor = 1.0 - ((backingheight -screenheight) /(mainheight -screenheight));
-const yvalue = -Main.getBoundingClientRect()。top * factor;这是我想到的几何草图。
I发现“ - main.getBoundingClientRect()。top”似乎比“我以前使用过的const scrolltopop = document.scrollingelement.scrolltop”更好地工作了。 main.getBoundingClientRect()。顶部基本上将距离从主元素的顶部返回到屏幕顶部,一旦您滚动了Main的顶部,就会成为负值。这就是为什么我添加了一个负数,但是Math.abs()也可以工作。const xvalue =“ center”; main.style.backgroundPosition = xvalue +“” + yvalue +“ px”;
在这里您只需将值插入背景。 现在,每次滚动时都会执行此功能。 Main,BackgroundHeight,Screen Height和Maintheight保持稳定,同时滚动,因此在加载或调整大小上执行的单独函数中初始化这些值是有意义的,除非Main自动更改其大小或在用户交互时更改其大小。我在测试Chrome时还了解到,Chrome在重新定位的背景图像大于1000x1000时具有巨大的性能问题,请记住这一点。