简体   繁体   中英

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. Anything involving JavaScript or CSS would work. I've done many Google searches and Stackoverflow searches and can't find exactly what I need.

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.

Assuming your element has an id of sprite , this should get you going:

<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';
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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