您的位置:首页 > Web前端 > JavaScript

js动画及封装

2019-07-06 14:38 92 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/Leejinian888/article/details/94856567
<!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;
}

.movebox {
width: 200px;
height: 200px;
background-color: deepskyblue;
position: absolute;
left: 0;
}

input {
margin: 10px;
}

.bg {
position: absolute;
top: 0px;
left: 800px;
border-left: 1px solid;
height: 800px;
}
</style>
</head>

<body>

<input type="button" name="" id="rt" value="向右走">
<input type="button" name="" id="lf" value="向左走">
<div class="movebox"></div>
<div class="bg"></div>
<script>

var btn1 = document.querySelector("#rt");   //获取元素
var btn2 = document.querySelector("#lf");
var movebox = document.querySelector(".movebox")
var timer;
btn1.onclick = function () {    //绑定点击事件
movefn(movebox, 15, "left", 800, function again() { //function是回调函数,即在这里再次调用;
movefn(movebox, 15, "top", 500, function again() {
movefn(movebox, 15, "left", 0, function again() {
movefn(movebox, 15, "top", 40)
})
})
})    //调用函数
}
btn2.onclick = function () {
movefn(movebox, 15, "left", 0)  //调用函数
}
function movefn(ele, speed, attr, Elength, again) {  //元素 步长 属性 目标长度
var current = parseInt(getStyle(ele, attr));  //获取初始距离的值
if (Elength < current) {    //判断目标距离是否小于初始距离,如果小于则是往左走,即步长为负
speed = -speed;
}
clearInterval(timer);   //开始执行就清除定时,防止点击累加
timer = setInterval(function () {
var begin = parseInt(getStyle(ele, attr));  //初始的距离,调用getStyle函数,因为调用后得到的结果带px单位,故加上parseInt取整
var step = begin + speed;   //开始的距离+步长累加=元素移动的距离
//当元素移动的距离小于目标长度 并且 步长小于0时,元素移动的距离就直接等于目标长度  (向左移动)
//比如,当目标距离等于0并且步长等-15,表示向左移,当元素移动的距离小于目标距离0时,就直接让元素移动的距离等于0;
//或者当元素移动的距离大于目标长度 并且 步长大于0时,元素移动的距离就直接等于目标长度  (向右移动)
//比如,当目标距离等于800并且步长等15,表示向右移,当元素移动的距离大于目标距离800时,就直接让元素移动的距离等于800;
if (step < Elength && speed < 0 || step > Elength && speed > 0) {   //做限定
step = Elength;
}
ele.style[attr] = step + "px";

if (step == Elength) {  //执行完毕清除定时器
clearInterval(timer);
again && again();  //回调函数的判断条件(当有这个函数名的时候才调用)
}
}, 30)
}

//封装过getStyle()函数 获取样式
function getStyle(ele, attr) {
if (window.getComputedStyle) {
return getComputedStyle(ele, null)[attr];   //标准
} else {
return ele.currentStyle[attr];  //兼容IE
}
}

</script>
</body>

</html>

效果图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: