确定元素是否在视口中-滚动期间-返回true / false

时间:2019-01-26 16:44:04

标签: javascript viewport

我正在编写一个小脚本,以确定某个元素是否在视口中...

我遇到的问题是我的变量RET总是以UNDEFINED的形式返回

myscript.js

function myScriptObj() {
  this.isElementInView = function (element, fullyInView) {  
    var RET;

    $(window).scroll(function () {
      var pageTop = $(window).scrollTop();
      var pageBottom = pageTop + $(window).height();
      var elementTop = $(element).offset().top;
      var elementBottom = elementTop + $(element).height();

      if (fullyInView === true) {
        RET = (pageTop < elementTop) && (pageBottom > elementBottom);
        console.log(`myscript.js: RET >>> ${RET}`);
        return RET;

      } else {
        RET = (elementTop <= pageBottom) && (elementBottom >= pageTop);
        console.log(`myscript.js: RET >>> ${RET}`);
        return RET;
      }
    });

    console.log(`myscript.js: RET >>> ${RET}`);
  }
}

在示例中index.html看起来像

<!DOCTYPE html>
<html lang="en">
<head>
  ...
</head>
<body>
  ...
  ...
  <div class="row center" id="banner">
    <img src="img/banner.jpg" width="514px" height="65px" border="0" />
  </div>
  ...
  <script src="js/myscript.js"></script>
  <script type="text/javascript">
    var myObj = new myScriptObj();
    var _isInView = myObj.isElementInView(document.getElementById("banner"), false);
    console.log(`index.html: myObj.RET >>> ${myObj.RET}`);

    if (_isInView) {
      console.log(`index.html: in view >>> ${_isInView}`);
    } else {
      console.log(`index.html: out of view >>> ${_isInView}`);
    } 
  </script>
  </body>
</html>

同样,myObj.RET是未定义的,但是,在函数isElementInView中,变量RET的值为true或false

有人可以告诉我我在想什么

0 个答案:

没有答案