我首先祝您美好的一天! 总结我的网站:主体是由标头和主体组成的。主要部分具有背景图像和元素。这些元素的(组合...

问题描述 投票:0回答:1
总结我的网站:主体是由标题和主体组成的。主要部分具有背景图像和元素。这些元素的(组合)高度是可变的,因为它取决于用户的字体大小,屏幕大小等。对于那些想要自己测试或需要它来回答我的问题的人,这是HTML和CSS代码:

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>

该代码的问题是它有效,但不能按照我的需要。当我使用恒定因素(例如0.5、0.3、0.7等)时,如果向下滚动滚动,则总会有背景图像和底部之间的空白,或者 - 这是相反的效果 - 当您向下滚动时,您不会到达图像的底部,从而切断零件。不断的因素仅适用于非常具体的情况,但我希望它到处都可以工作。

因此,我需要的是一个公式,该公式会自动计算该因子,无论您如何调整屏幕大小,无论标头,主或主元素的高度如何,该公式始终确保背景图像的底部与网站的底部完美匹配。如果您能帮助我,我真的很感激!

我决定分享我自己想出的答案,以防我之后的其他人有同样的问题,并希望在这里找到答案:

javascript html css formula parallax
1个回答
0
投票

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时具有巨大的性能问题,请记住这一点。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.