繁体   English   中英

在JavaScript中达到目标div时触发操作

[英]Trigger action when reaching a target div in Javascript

我正在用PHP和MySQL输出结果集,每个结果都包装在DIV中。 一旦用户滚动到浏览器窗口的底部,JavaScript函数就会触发操作。

$(window).scroll(function(){
  if ($(window).scrollTop() == $(document).height() - $(window).height()){
    trigger_funtion();
  }
}); 

PHP结果的每个项目(类“ .item”)都放入包含所有项目的通用包装DIV(类“ .results”)中。

如何在上面更改此功能,以便用户在从结果集创建的最后一个DIV中“滚动”或“到达”时立即触发操作,而不是在用户点击浏览器窗口底部时触发操作?

我已经尝试了以下方法,但是它不起作用

$(window).scroll(function(){
  if  ($(window).scrollTop() == $(".results .item:last")){
    trigger_funtion();
  }
}); 

您需要使用.position()。top ,我建议使用> =而不是==,因为您不能依赖于相等的数字

if  ($(window).scrollTop() >= $(".results .item:last").position().top)

要么

var winHeight = $(window).height(); // viewport 
if  ($(window).scrollTop()+winHeight >= $(".results .item:last").position().top)

这是最后一项到达顶部时的代码

现场演示

$(function() {
  var $item = $(".results .item:last"); // cache element  
  $(window).scroll(function(){
    var itemTop = $item.position().top-10;  // subtract some pixels from the  item 
    var winScrollTop =$(window).scrollTop();
    window.console && console.log(winScrollTop,itemTop); // remove when happy
    if  (winScrollTop>=itemTop) { 
      window.console && console.log("reached!",winScrollTop,itemTop); remove when happy
      $item.html("REACHED!");
    }
  });
}); 

当它触底时

现场演示

$(function() {
  var $item = $(".results .item:last"); // cache element  
  $(window).scroll(function(){
    var itemTop = $item.position().top-10;  // subtract some pixels from the  item 
    var winScrollTop =$(window).scrollTop();
    var winHeight = $(window).height();  
    window.console && console.log(winScrollTop,itemTop); // remove when happy
    if  (winScrollTop+winHeight>=itemTop) { 
      window.console && console.log("reached!",winScrollTop,itemTop); // remove when happy
      $item.html("REACHED!");
    }
  });
}); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM