Function parameters

  1. Obj: The object to animate
  2. Attr: Style to execute animation, such as: left top width height
  3. Target: The target position to execute the animation
  4. Speed: The speed of movement (positive numbers move to the right, negative numbers move to the left)
  5. Callback: Callback function, which will be executed after the animation has finished executing
  • Code implementation
Function move(obj, attr, target, speed, callback) {// Close the previous timer clearInterval(obj.timer); Var current = parseInt(getStyle(obj, attr)); // If (current > target) {// If (current > target) {// If (current > target) {speed = -speed; } // Start a timer to execute the animation effect // Add a timer property to the object executing the animation, Obj. Timer = setInterval(function() {var oldValue = parseInt(getStyle(obj, attr)); Var newValue = oldValue + speed; // Check whether newValue is greater than 800 // If you move from 800 to 0 // If you move to the left, check whether newValue is smaller than target // If you move to the right, Need to determine whether newValue is greater than the target, the if ((speed < 0 && newValue < target) | | (speed > 0 && newValue > target)) {newValue = target; } // set the newValue to box1 obj.style[attr] = newValue + "px"; // If (newValue == target) {// If the target is reached, turn off the timer clearInterval(obj.timer); Callback && callback(); }}, 30); }Copy the code
/*
 * 定义一个函数,用来获取指定元素的当前的样式
 * 参数:
 * 		obj 要获取样式的元素
 * 		name 要获取的样式名
 */
function getStyle(obj, name) {

	if(window.getComputedStyle) {
		//正常浏览器的方式,具有getComputedStyle()方法
		return getComputedStyle(obj, null)[name];
	} else {
		//IE8的方式,没有getComputedStyle()方法
		return obj.currentStyle[name];
	}

}
Copy the code