滚动后检查元素是否按百分比区域可见?

时间:2015-12-03 22:56:00

标签: javascript scroll visibility percentage getboundingclientrect

如何按百分比区域检测可见元素 50%或更多? visibility element by percentage JS

使用Javascript:

var i = setInterval(function() {

var el = document.getElementById('test');
var rect = el.getBoundingClientRect();

if(
  rect.top >= 0 &&
  rect.left >= 0 &&
  rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
  rect.right <= (window.innerWidth || document.documentElement.clientWidth) == true) {
  var div = document.getElementById('log').innerHTML = 'Visible';
  //clearInterval(i);
}
  else {
    var div = document.getElementById('log').innerHTML = 'No visible';
  }

},1000);

JSFIDDLE

1 个答案:

答案 0 :(得分:0)

我将50%的元素高度(rect.height / 2)添加到条件中。现在它检测到元素只有50%可见。

var i = setInterval(function() {

var el = document.getElementById('test');
var rect = el.getBoundingClientRect();
  console.log(window.innerHeight)  
  console.log(rect) 
if(
  rect.top >= 0 &&
  rect.left >= 0 &&
  rect.bottom <= (window.innerHeight+(rect.height/2) || document.documentElement.clientHeight+(rect.height/2) ) &&
  rect.right <= (window.innerWidth || document.documentElement.clientWidth) == true) {
  var div = document.getElementById('log').innerHTML = 'Visible';
  //clearInterval(i);
}
  else {
    var div = document.getElementById('log').innerHTML = 'No visible';
  }
},1000);