部分可见时滚动并运行代码(纯Javascript)

时间:2016-11-26 19:19:56

标签: javascript



	function animateValue(id, start, end, duration) {
    var range = end - start;
    var current = start;
    var increment = end > start? 1 : -1;
    var stepTime = Math.abs(Math.floor(duration / range));
    var obj = document.getElementById(id);
    var timer = setInterval(function() {
        current += increment;
        obj.innerHTML = current;
        if (current == end) {
            clearInterval(timer);
        }
    }, stepTime);
}
animateValue("num1", 0, 75, 10000);

var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;

if(scrollTop > 400){
	animateValue("num2", 0, 75, 10000);
}

.box{
  height:500px;
}

<h1 id="num1">75</h1>
<div class="box"></div>
<h1 id="num2">75</h1>
&#13;
&#13;
&#13;

我需要在id =&#34; num2&#34;上运行从0到75的数字,如id =&#34; num1&#34;工作中。但我需要id =&#34; num2&#34;在页面之后滚动向下滚动。这是一个挑战,因为我不能使用像Jquery,angular JS等任何库。我需要使用纯JavaScript

1 个答案:

答案 0 :(得分:0)

我添加了一些滚动和调整大小的事件(两者都可以&#34;显示&#34;目标元素)。使用.getBoundingClientRect()时,我们不需要滚动位置,因为它会向我们显示目标top位置,具体取决于滚动位置。

https://jsfiddle.net/q8ww67tj/

&#13;
&#13;
function animateValue(id, start, end, duration) {
	var range = end - start;
	var current = start;
	var increment = end > start? 1 : -1;
	var stepTime = Math.abs(Math.floor(duration / range));
	var obj = document.getElementById(id);
	var timer = setInterval(function() {
		current += increment;
		obj.innerHTML = current;
		if (current == end) {
			clearInterval(timer);
		}
	}, stepTime);
}
animateValue("num1", 0, 75, 10000);

triggered = false;
window.addEventListener('load', recalculate);
window.addEventListener('scroll', recalculate);
window.addEventListener('resize', recalculate);

function recalculate() {
	var height = document.body.clientHeight,
		targetRect = document.getElementById('num2').getBoundingClientRect();
		targetY = targetRect['top'],
		targetHeight = targetRect['height'];
	
	if (targetY + targetHeight < height) {
		if (!triggered) {
			triggered = true;
			animateValue("num2", 0, 75, 10000);
		}
	}
}
&#13;
.box {
  height: 1000px;
}
&#13;
<h1 id="num1">75</h1>
<div class="box"></div>
<h1 id="num2">75</h1>
&#13;
&#13;
&#13;