【问题标题】:PagePiling.js determine if elements are in viewPagePiling.js 确定元素是否在视图中
【发布时间】:2018-09-15 23:10:37
【问题描述】:

我正在尝试在某些文本出现时对其进行动画处理。一切正常,但是当我引入 pagepiling.js 时,用于确定我的元素是否在视图中的函数返回 false。这是函数:

function elementInViewport(el) {
    var top    = el.offsetTop;
    var left   = el.offsetLeft;
    var width  = el.offsetWidth;
    var height = el.offsetHeight;

    while (el.offsetParent) {
        el = el.offsetParent;
        top += el.offsetTop;
        left += el.offsetLeft;
    }

    return (
        top < (window.pageYOffset + window.innerHeight) &&
        left < (window.pageXOffset + window.innerWidth) &&
        (top + height) > window.pageYOffset &&
        (left + width) > window.pageXOffset
    );
}

对可能出现的问题有任何想法吗?

【问题讨论】:

    标签: javascript pagepiling.js


    【解决方案1】:

    请查看pagePiling.js callbacks 的使用方法,例如afterLoadonLeave

    您也可以在 github 存储库的 examples 文件夹中查看 the available example

    【讨论】:

      【解决方案2】:

      这个功能应该可以工作:

      function isInView(el) {
        let bb = el.getBoundingClientRect();
        return bb.top <= window.innerHeight && bb.bottom >= 0
          && bb.left <= window.innerWidth && bb.right >= 0;
      }
      

      这是一个演示:

      document.onscroll = function() {
        document.querySelector('.status').textContent = isInView(document.querySelector('.element')) ? 'IN' : 'OUT';
      }
      
      function isInView(el) {
        let bb = el.getBoundingClientRect();
        return bb.top <= window.innerHeight && bb.bottom >= 0
          && bb.left <= window.innerWidth && bb.right >= 0;
      }
      .before,
      .element,
      .after {
        height: 200vh;
        background: wheat;
      }
      .element {
        background: teal;
      }
      .status {
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 1em;
        background: silver;
      }
      <div class="before">Before</div>
      <div class="element">Element</div>
      <div class="after">After</div>
      <div class="status">...</div>

      【讨论】:

        猜你喜欢
        • 2020-04-26
        • 2021-04-15
        • 1970-01-01
        • 2018-08-03
        • 2016-02-07
        • 1970-01-01
        • 2011-07-12
        • 1970-01-01
        • 2011-03-20
        相关资源
        最近更新 更多