简体   繁体   English

如何判断屏幕上是否呈现HTML元素?

[英]How might I tell if an HTML element is being rendered on the screen?

I'd like an element to do a CSS3 animation once the page is scrolled down enough for it to be visible, and I'm wondering if there's any way to accomplish this. 我希望元素在页面向下滚动到足以使其可见后执行CSS3动画处理,并且我想知道是否有任何方法可以完成此操作。 Anything involving JavaScript or CSS would work. 任何涉及JavaScript或CSS的东西都可以使用。 I've done many Google searches and Stackoverflow searches and can't find exactly what I need. 我已经做了很多Google搜索和Stackoverflow搜索,但找不到我真正需要的东西。

Depending on the complexity of your layout, it could be as simple as finding the scroll position, the height of the window, and where the element is on the page. 根据布局的复杂程度,它可能很简单,例如查找滚动位置,窗口的高度以及元素在页面上的位置。

function scrollEvent() {
  var el = document.getElementsByTagName('a')[0];
  var body = document.getElementsByTagName('body')[0];
  var posY = (window.innerHeight + body.scrollTop) - el.offsetTop;
  var onScreen = (posY > 0 && posY < window.innerHeight) ? true : false;
}

window.onscroll = scrollEvent;

Use the same technique if you're worried about horizontal positioning, as well. 如果您担心水平定位,也可以使用相同的技术。

Put your CSS3 animation style in a class, but don't assign it to your element until it has been scrolled completely into view. 将您的CSS3动画样式放在一个类中,但在将其完全滚动到视图中之前,请勿将其分配给您的元素。

Assuming your element has an id of sprite , this should get you going: 假设您的元素的idsprite ,这应该可以帮助您:

<style>
  .animate {
    //CSS3 animation style
  }
</style>

window.onscroll= function() {
  var sprite = document.getElementById('sprite');
  if(sprite.getBoundingClientRect().top>=0 && sprite.getBoundingClientRect().bottom<=window.innerHeight) {
    sprite.className= 'animate';
  }
}

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

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