jQuery:当div进入视图时,如何触发事件?

Mat*_*tty 27 jquery

当页面滚动到足以让div进入视图时,是否有某些方法可以使用jQuery触发事件?

rcr*_*ens 13

我想你必须挂钩滚动事件并手动检查.这是一个类似的问题:

滚动后检查元素是否可见

希望有所帮助.

短发


小智 9

如果你只需要开一次:

$(window).scroll(function(){
  // This is then function used to detect if the element is scrolled into view
  function elementScrolled(elem)
  {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
  }

  // This is where we use the function to detect if ".box2" is scrolled into view, and when it is add the class ".animated" to the <p> child element
  if(elementScrolled('. box2')) {


  // Your function here

  }
});
Run Code Online (Sandbox Code Playgroud)

完整答案:https://www.thewebtaylor.com/articles/how-to-detect-if-an-element-is-scrolled-into-view-using-jquery