计时对象的可见时间

时间:2018-06-24 17:13:59

标签: javascript timer viewport onscroll

我想知道一个对象(至少50%)是否可见。这就是我对这段代码所做的。

我想改善代码以了解该对象可见的时间。我不知道如何在到达视口时获取日期,以及在不再可见时获取日期。

我的代码每次滚动时都会在控制台中返回所有“ true”和“ false”,因此,可以在第一个“ true”处获取日期,并在它变为“ false”时获取新的Date吗?

预先感谢

<html>
<head>
</head>
<body>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<img id="image_test" width="300" height="200" src="https://image.flaticon.com/icons/svg/23/23656.svg" alt="100" />
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<script>
    window.onload = function() {
		var isInViewport = function (elem) {
    		var bounding = elem.getBoundingClientRect();
    		return (
        	bounding.top >= -0.5 * elem.height &&
        	bounding.left >= 0 &&
       		bounding.bottom <= 1.15 * (window.innerHeight || document.documentElement.clientHeight) && 
        	bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
    		);
		};
		
		var player = document.getElementById('image_test');
		
		window.addEventListener('scroll', function () {
			canUserSeeIt = isInViewport(player);
			console.log(canUserSeeIt);
		}, false);

};		
    
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

修改后的代码将告诉:

  • 对象可见的时间(以毫秒为单位)
  • 当对象变得不可见

    window.onload = function() {
        var start = new Date();
        var stillVisible = true;
        var isInViewport = function (elem) {
            var bounding = elem.getBoundingClientRect();
            return (
            bounding.top >= -0.5 * elem.height &&
            bounding.left >= 0 &&
            bounding.bottom <= 1.15 * (window.innerHeight || document.documentElement.clientHeight) && 
            bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
            );
        };
    
        var player = document.getElementById('image_test');
    
        window.addEventListener('scroll', function () {
            canUserSeeIt = isInViewport(player);
            if (stillVisible && !canUserSeeIt){
              var now = new Date(); // Becomed invisible
              stillVisible = false;
              var visibleTime = now - start; // How long has been visible
              console.log(now, visibleTime);
            }
            console.log(canUserSeeIt);
        }, false);
    

    };

https://jsbin.com/wuqegedeyo/edit?html,output