jQuery如果视口中的DOM元素检查总是返回true并滚动

jQuery如果视口中的DOM元素检查总是返回true并滚动,jquery,scroll,visibility,viewport,Jquery,Scroll,Visibility,Viewport,我试图弄清楚如何在滚动期间检查windows视口中是否可见DOM元素,我已经使用了许多方法和许多插件,但我一事无成。看起来像是在我将视口检查附加到窗口时。滚动它只是不起作用: $(window).scroll(function() { if(checkIfXInViewport) { // this is getting executed ALL THE TIME } else { // this never happens even if X is NOT in v

我试图弄清楚如何在滚动期间检查windows视口中是否可见DOM元素,我已经使用了许多方法和许多插件,但我一事无成。看起来像是在我将视口检查附加到窗口时。滚动它只是不起作用:

$(window).scroll(function() {
  if(checkIfXInViewport) { 
    // this is getting executed ALL THE TIME 
  } else { 
   // this never happens even if X is NOT in viewport }
}
}))

下面是一个使用:(using)的示例。运行控制台,它始终返回“可见”,即使标题不在视口中。。。。为什么?


我做错了什么?

这是我用来检测视口中至少有50%的元素时所做的,然后做一些事情。您可以调整以检测它变为可见的瞬间

// Create jQuery Method

jQuery.fn.isOnScreen = function(){

  var win = $(window);

  var viewport = {
    top : win.scrollTop(),
    left : win.scrollLeft()
  };
  viewport.right = viewport.left + win.width();
  viewport.bottom = viewport.top + win.height();

  var elemtHeight = this.height()/2;
  elemtHeight = Math.round(elemtHeight);r

  var bounds = this.offset();
  bounds.top = bounds.top + elemtHeight;
  bounds.right = bounds.left + this.outerWidth();
  bounds.bottom = bounds.top + this.outerHeight();

  return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

}

//Usage:
$(window).scroll(function(){
  if( $('#your-element').isOnScreen() ){
    // do something
  }
  else {
    // element not in viewport
  }
});
//创建jQuery方法
jQuery.fn.isOnScreen=函数(){
var win=$(窗口);
变量视口={
top:win.scrollTop(),
左:win.scrollLeft()
};
viewport.right=viewport.left+win.width();
viewport.bottom=viewport.top+win.height();
var elemtHeight=this.height()/2;
elemtHeight=数学圆(elemtHeight);r
var bounds=this.offset();
bounds.top=bounds.top+元素高度;
bounds.right=bounds.left+this.outerWidth();
bounds.bottom=bounds.top+this.outerHeight();
返回(!(viewport.rightbounds.right | | viewport.bottombounds.bottom));
}
//用法:
$(窗口)。滚动(函数(){
if($(“#您的元素”).isOnScreen(){
//做点什么
}
否则{
//元素不在视口中
}
});