简体   繁体   English

使用Vanilla JS在小屏幕上滚动动画问题

[英]On scroll animation issue on small screens using Vanilla JS

I've created an animation for my website to change a certain element (for example its background colour) while scrolling using Vanilla JS. 我已经为我的网站创建了一个动画,以在使用Vanilla JS滚动时更改某些元素(例如其背景色)。 For this I have used the window.onscroll property and I trigger the animation when window.scrollY reaches a specific position, my code is: 为此,我使用了window.onscroll属性,并在window.scrollY到达特定位置时触发了动画,我的代码是:

window.addEventListener('scroll', () => {
   if (window.scrollX >= 1000) {
      box.style = "background:red"
   }
})

It looks great when I am editing on my big screen resolution, but if I look at the page on my laptop, the animation gets messed up because the innerWidth and innerHeight of the screen are different. 当我在大屏幕分辨率上进行编辑时,它看起来很棒,但是如果我在笔记本电脑上查看页面,动画会变得混乱,因为屏幕的innerWidthinnerHeight不同。 I want to trigger the animation dynamically if it reaches a certain section of the page without having to worry about the scroll position. 如果动画到达页面的特定部分,我想动态地触发动画,而不必担心滚动位置。

Does anyone have any ideas about how I can fix this? 有人对我该如何解决有任何想法吗?

I think using getBoundingClientRect() solves your problem. 我认为使用getBoundingClientRect()解决了您的问题。 You basically do something like this: 您基本上会执行以下操作:

var my_box = document.getElementById('my-box');
var rect = my_box.getBoundingClientRect();

The rect variable now contains an Object which includes a top and a left property with values that are relative to the viewport. rect变量现在包含一个Object,该Object包含一个topleft属性,这些属性的值相对于视口。

https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM