Use native js simple animation effects

Use native js simple animation effects

We know that, with the animate jQuery method provides, we can easily achieve some common js animation. As for the style can not be directly represented by the value of color, we can be achieved by introducing a number of jQuery plug-ins. But with the popularity of front-end component-based development, jQuery lot of DOM manipulation has become very redundant, is being phased out from the front-end technology stack. So how to use native js to achieve animation effects similar to jQuery in it? Here we will use the native js achieve a simple div allow uniform widening animation.

Target effect

Click the button to the div widening from 100 pixels to 200 pixels. The initial HTML code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>简单js动画的实现</title>
    <style>
        #nav{
        	margin-top: 20px;
            width: 100px;
            height: 100px;
            background-color: #409eff;
        }
    </style>
</head>
<body>
<button onclick="run()">加宽</button>
<div id="nav"></div>
</body>
<script>
	//需要应用动画效果的目标元素
	var elem = document.getElementById('nav');
	//动画配置,为了方便,这里只针对width属性,duration表示动画持续时间
    var options = {
        width: '200px',
        duration: 1000
    };
    //启动动画
    function run(){
    	animate.call(elem, options);
    }
    //动画逻辑
	function animate(options){
		//动画的具体实现,后面的所有代码均位于该函数内
		...
	}
</script>
<html>

Initial results are as follows:
Initial results

Fundamental

The rationale for using js animation effects are achieved with window.setInterval (logic, time) to control the overall operation of the animation process. Logic for calculating and setting the style of the current frame, time given animation refresh rate (i.e., the spacer recalculated every style, not consider the task blocked).

So logic how to calculate the value of the current frame width div it? First we need to get the original width and end width div, then according to the percentage of the current animation performed to calculate the current width value, which requires the aid of three parameters to determine the time. One is the start time of the animation, we have to get the number of milliseconds the current time in the form of a simple function, the code is as follows:

//定时器
var timer = null;
//div的初始宽度和结束宽度
var startWidth = parseInt(window.getComputedStyle(elem)['width']);
var endWidth = parseInt(options.width);
	
function createTime(){
	//返回当前日期距1970年1月1日午夜(GMT 时间)之间的毫秒数,一种简化写法
	return (+new Date);
}
var startTime = createTime();

Another is the duration of the animation duration, we get from the parameter configuration. The third is the current time, we get the dynamic logic function. According to these three parameters, we can calculate the time remaining in the current logic of the animation:

function logic(){
	//开始时间 + 持续时间 - 当前时间,结果即为动画的剩余时间,当剩余时间小于0则置0,表示动画结束
	var remaining = Math.max(0, startTime + options.duration - createTime());

Depending on the duration and the remaining time animation animation, we can easily calculate the percentage of the current animation execution, namely:

	//remaining/duration即为动画剩余的百分比,用1去减,得到已执行的百分比
	var percent = 1 - (remaining / options.duration); 

According to the percentage of the animation has been performed, we can calculate the current frame style elements:

	//(结束宽度 - 开始宽度)* 百分比 + 开始宽度,即为当前帧div的实际宽度
	var nowWidth = ( endWidth - startWidth ) * percent + startWidth;

We then define a function setStyle to set the width to div:

	function setStyle(nowWidth){
		elem.style['width'] = nowWidth + 'px';
	}

We judge whether the current animation percent by the end, if completed, would set the style and clear the timer, otherwise you can only set style:

	if(percent === 1){
		setStyle(nowWidth);
		clearInterval(timer);
		timer = null;
	} else {
		setStyle(nowWidth);
	}
}

Finally, we start the timer function outside of logic, set the frame refresh rate of 13 ms (default refresh rate of jQuery):

timer = setInterval(logic, 13);

to sum up

The complete code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>简单js动画的实现</title>
    <style>
        #nav{
        	margin-top: 20px;
            width: 100px;
            height: 100px;
            background-color: #409eff;
        }
    </style>
</head>
<body>
<button onclick="run()">加宽</button>
<div id="nav"></div>
</body>
<script>
//需要应用动画效果的目标元素
var elem = document.getElementById('nav');
//动画配置,为了方便,这里只针对width属性,duration表示动画持续时间
var options = {
    width: '200px',
    duration: 1000
};
//点击按钮启动动画
function run(){
    animate.call(elem, options);
}
//动画逻辑
function animate(options){
	//定时器
	var timer = null;
	//div的初始宽度和结束宽度
	var startWidth = parseInt(window.getComputedStyle(elem)['width']);
	var endWidth = parseInt(options.width);
	
	function createTime(){
		//返回当前日期距1970年1月1日午夜(GMT 时间)之间的毫秒数,一种简化写法
		return (+new Date);
	}
	var startTime = createTime();

	function logic(){
		//开始时间 + 持续时间 - 当前时间,结果即为动画的剩余时间,当剩余时间小于0则置0,表示动画结束
		var remaining = Math.max(0, startTime + options.duration - createTime());
		//remaining/duration即为动画剩余的百分比,用1去减,得到已执行的百分比
		var percent = 1 - (remaining / options.duration); 
		//(结束宽度 - 开始宽度)* 百分比 + 开始宽度,即为当前帧div的实际宽度
		var nowWidth = ( endWidth - startWidth ) * percent + startWidth;
		function setStyle(nowWidth){
			elem.style['width'] = nowWidth + 'px';
		}
		if(percent === 1){
			setStyle(nowWidth);
			clearInterval(timer);
			timer = null;
		} else {
			setStyle(nowWidth);
		}
	}
	timer = setInterval(logic, 13);
}
</script>
<html>

This example simply implement changes in the width of the element, but can learn the basic principles of animation js execution. I.e. by setInterval (logic, time) to control the animation execution, style Logic for calculating each frame, time frame refresh rate was such continuous calculation and set the style elements, i.e. the formation of animation.

Published 37 original articles · won praise 90 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41694291/article/details/93340607