JS特效——简单的匀速平移动画
程序员文章站
2022-06-15 14:52:37
...
知识点
- 一般实现动画的两种方式,定位和margin-left
运行效果
点击开始开始运动
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box{
height: 100px;
width: 100px;
background-color: red;
}
</style>
</head>
<body>
<button id="btn">开始动画</button>
<div id="box"></div>
<script>
window.addEventListener('load',function (ev) {
// 1. 获取需要的标签
var btn = document.getElementById('btn');
var box = document.getElementById('box');
var intervalID = null, begin = 0, step = 50, target = 600;
// 2. 事件触发
btn.addEventListener('click',function (ev1) {
// 2.1 清除定时器
clearInterval(intervalID);
// 2.2 设置定时器
intervalID = setInterval(function () {
// 改变起始值
begin += step;
// 判断
if (begin >= target){
begin = target;
clearInterval(intervalID);
}
// 改变盒子
box.style.marginLeft = begin + 'px';
}, 50);
});
});
</script>
</body>
</html>
封装成函数的时候,根据不同人的思想,可以有不同的封装方式。
封装版本1.0
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box{
height: 100px;
width: 100px;
background-color: red;
}
</style>
</head>
<body>
<button id="btn">开始动画</button>
<div id="box"></div>
<script>
window.addEventListener('load',function (ev) {
linearAnimation('btn','box',50,800)
});
function linearAnimation(btnID, boxID, step, target){
var btn = document.getElementById(btnID);
var box = document.getElementById(boxID);
var intervalID = null, begin = 0, step_len = step||0 ;
btn.addEventListener('click',function (ev1) {
clearInterval(intervalID);
intervalID = setInterval(function () {
begin += step_len;
if (begin >= target){
begin = target;
clearInterval(intervalID);
}
box.style.marginLeft = begin + 'px';
}, 50);
});
}
</script>
</body>
</html>
封装版本2.0
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box{
height: 100px;
width: 100px;
background-color: red;
}
</style>
</head>
<body>
<button id="btn">开始动画</button>
<div id="box"></div>
<script>
window.addEventListener('load',function (ev) {
document.getElementById('btn').onclick = function (ev1) {
linearAnimation('box',50,800);
}
});
function linearAnimation( boxID, step, target){
var box = document.getElementById(boxID);
var intervalID = null, begin = 0, step_len = step||0 ;
clearInterval(intervalID);
intervalID = setInterval(function () {
begin += step_len;
if (begin >= target){
begin = target;
clearInterval(intervalID);
}
box.style.marginLeft = begin + 'px';
}, 50);
}
</script>
</body>
</html>