<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0%;
padding: 0%;
}
#box1{
width: 100px;
height: 100px;
background-color:red;
/* 如果需要移动位置,就必须要开启位置定位 */
position: absolute;
}
</style>
<script>
window.onload = function(){
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var box1 = document.getElementById('box1');
// 向右移动
btn1.onclick = function(){
// clearInterval(timer);
// // 开启一个定时器,用来执行动画效果.
// timer = setInterval(function(){
// // 获取box1的原来left值,parseInt()函数可解析一个字符串,并返回一个整数。
// // 也可以用box1.style.left来获取left值,但使用getStyle()函数更加高级一些.
// var oldValue = parseInt(getStyle(box1, 'left'));
// var newValue = oldValue + 20;
// box1.style.left = newValue + 'px';
// if(newValue >= 800){
// clearInterval(timer);
// alert(box1.style.left);
// };
// }, 50);
move(box1, 800, 20);
};
// 向左移动
btn2.onclick = function(){
// clearInterval(timer);
// timer = setInterval(function(){
// var oldValue = parseInt(getStyle(box1, 'left'));
// var newValue = oldValue - 20;
// box1.style.left = newValue + 'px';
// if (newValue <=0){
// clearInterval(timer);
// };
// }, 50);
move(box1, 0, 20);
};
};
// 定义一个变量,用来保存定时器标识
var timer;
// 写一条动画的函数:
/*
参数:
obj:要执行动画的对象
target:执行动画的目标位置
speed:移动的速度(正数向右移动,负数向左移动)
*/
function move(obj, target, speed){
// 关闭上一个定时器
clearInterval(timer);
// 获取元素目前位置
var current = parseInt(getStyle(box1, 'left'));
// 判断速度正负值
// 如果从0向800移动,则speed为正
// 如果从800向0移动,则speed为负
if(current > target){
speed = -speed;
};
// 开启一个定时器,用来执行动画效果
timer = setInterval(function(){
var oldValue = parseInt(getStyle(obj, 'left'));
// 在旧值的基础上添加
var newValue = oldValue + speed;
// 判断newValue是否大于800
// 从800向0移动
// 向左移动时,需要判断newValue是否小于target
// 向右移动时,需要判断vewValue是否大于target
if(speed < 0 && newValue < target || speed > 0 && newValue > target){
newValue = target;
};
// 将新值设置给box1
obj.style.left = newValue + 'px';
// 当元素移动到0px时,将其停止执行动画
if(newValue == target){
// 达到目标,关闭定时器
clearInterval(timer);
}
}, 50);
}
/*
定义一个函数, 用来获取指定元素的当前样式
参数:
obj 要获取样式的元素
name 要获取的样式名
*/
function getStyle(obj, name){
if(window.getComputedStyle){
// 正常游览器的方式,具有getComputedStyle()方法
return getComputedStyle(obj, null)[name];
}else{
// IE8的方式,没有getComputedStyle()方法
return obj.currentStyle[name];
};
};
</script>
</head>
<body>
<button id="btn1">点击向右移动</button>
<button id="btn2">点击向左移动</button>
<br><br>
<div id="box1"></div>
</body>
</html>
JS基础-定时器应用2(精)
最新推荐文章于 2022-01-30 12:20:58 发布