如何检测用户是否滚动到<embed />元素的末尾?

时间:2019-01-30 15:50:17

标签: javascript jquery html pdf scroll

如何检测用户是否滚动到<embed>元素的结尾?

<embed src="contract.pdf" type="application/pdf" width="800" height="800" id="contractPDF">  

我使用了这段代码,但是它不起作用:

$('#contractPDF').bind('scroll', function() {
  if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {   
    alert("end reched");
  }
});

1 个答案:

答案 0 :(得分:0)

首先,您需要知道元素的开始位置和结束位置,以便在向下滚动时知道是否已通过该点。

$(window).scroll(function() {

    // Fetch the embed container.
    var container = $('#contractPDF');

    // Height of our window.
    var windowHeight = $(window).height();
  
  // Container information.
  var containerHeight = $(container).height();
  var containerBottom = container.offset().top + containerHeight;

    // Location of our window in our page.
    var windowLocation = $(this).scrollTop();

   // Check if we are past it.
   if (windowLocation + windowHeight > containerBottom) { 
    alert('reached');
   }

});
#contractPDF {
  height: 900px;
  width: 200px;
  background-color: blue;
  position:relative;
  display:block;
}

#contractPDF2 {
  height: 900px;
  width: 200px;
  background-color: red;
  position:relative;
  display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="contractPDF"></div>
<div id="contractPDF2"></div>