<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <style>
    body { height: 2000px; position: relative;}
    .box {
      position: absolute;
      z-index: 9;
      left: 0;
      top: 1000px;
      width: 100px;
      height: 100px;
      background-color: #f45;
    }
  </style>
</head>
<body>
  <div class="box"></div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
    (function ($) {
      $(document).on('scroll', function () {
        var obj = $('.box');
        var clientHeight = $(window).height();
        var scrollTop = $(document).scrollTop();
        var offsetTop = obj.offset().top;
        var objHeight = obj.height();
        if(offsetTop < scrollTop + clientHeight && offsetTop + objHeight > scrollTop) {
          console.log('u can see me!')
        }
      })
      window.onscroll = function () {
        var obj = document.getElementsByClassName('box')[0];
        var clientHeight = window.innerHeight;
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        var offsetTop = obj.offsetTop;
        var objHeight = obj.offsetHeight;
        if(offsetTop < scrollTop + clientHeight && offsetTop + objHeight > scrollTop) {
          console.log('u can see me!')
        }
      }
    })(jQuery);
  </script>
</body>
</html>

 

posted on 2017-07-17 11:06  百里登风  阅读(3206)  评论(0编辑  收藏  举报