1

就像检查下面的“演示 div”

<div class="call" style="margin-top:100px;">
   hi
</div>
<div class="call" style="margin-top:900px;">
  hello
</div>

如果屏幕上的任何上述 div 使用类名返回 true,则在滚动时我使用下面的脚本始终返回 true,如何解决?

<script>
jQuery.expr.filters.offscreen = function(el) {
return (
      (el.offsetLeft + el.offsetWidth) < 0 
      || (el.offsetTop + el.offsetHeight) < 0
      || (el.offsetLeft > window.innerWidth || el.offsetTop > window.innerHeight)
 );
};

$(window).scroll(function () {
alert($('.call').is(':offscreen'))
});
</script>
4

1 回答 1

0

try this

$(document).scroll(function () {
                if (isOnScreen($('.call:eq(0)'))) {
                    // $('.call:eq(0)') is visible on screen
                }

            });

    //this function return element is currently visible on screen or not in true / false
            function isOnScreen(elem) {
                var docViewTop = $(window).scrollTop();
                var docViewBottom = docViewTop + $(window).height();

                var elemTop = $(elem).offset().top;
                var elemBottom = elemTop + $(elem).height();

                return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
            }

for demo

<div class="call" style="margin-top: 100px;">
    hi
</div>
<label class="label1" style="margin-top: 500px;">
</label>
<label class="label2" style="margin-top: 20px;">
</label>
<div class="call" style="margin-top: 500px;">
    hello
</div>
   <script type="text/javascript">
        $(document).scroll(function () {
            if (isOnScreen($('.call:eq(0)'))) {
                $('.label1').text('first div show') // if first call class div is visible msg display in lable
            }
            else {
                $('.label1').text('first div hide')
            }
            if (isOnScreen($('.call:eq(1)'))) {
                $('.label2').text('second div show')// if second call class div is visible msg display in lable
            }
            else {
                $('.label2').text('second div hide')
            }

        });
        function isOnScreen(elem) {
            var docViewTop = $(window).scrollTop();
            var docViewBottom = docViewTop + $(window).height();

            var elemTop = $(elem).offset().top;
            var elemBottom = elemTop + $(elem).height();

            return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
        }
    </script>
于 2013-06-22T09:42:24.343 回答