温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

原生JS封装animate运动框架的示例分析

发布时间:2021-07-23 11:49:14 来源:亿速云 阅读:158 作者:小新 栏目:web开发

小编给大家分享一下原生JS封装animate运动框架的示例分析,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

如下所示:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
div {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
top: 50px;
border-radius: 50%;
}
</style>
</head>
<body>
<button id="btn200">200</button>
<button id="btn400">400</button>
<div id="box"></div>
</body>
</html>
<script>
var btn200 = document.getElementById("btn200");
var btn400 = document.getElementById("btn400");
var box = document.getElementById("box");
btn200.onclick = function() {
animate(box,{width: 200, top: 100,left: 200,opacity:40,zIndex:3},function(){alert("我来了")});
}
btn400.onclick = function() {
animate(box,{top:500,opacity:10});
}
// 多个属性运动框架 添加回调函数
function animate(obj,json,fn) { // 给谁 json
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var flag = true; // 用来判断是否停止定时器 一定写到遍历的外面
for(var attr in json){ // attr 属性 json[attr] 值
//开始遍历 json
// 计算步长 用 target 位置 减去当前的位置 除以 10
// console.log(attr);
var current = 0;
if(attr == "opacity")
{
current = Math.round(parseInt(getStyle(obj,attr)*100)) || 0;
console.log(current);
}
else
{
current = parseInt(getStyle(obj,attr)); // 数值
}
// console.log(current);
// 目标位置就是 属性值
var step = ( json[attr] - current) / 10; // 步长 用目标位置 - 现在的位置 / 10
step = step > 0 ? Math.ceil(step) : Math.floor(step);
//判断透明度
if(attr == "opacity") // 判断用户有没有输入 opacity
{
if("opacity" in obj.style) // 判断 我们浏览器是否支持opacity
{
// obj.style.opacity
obj.style.opacity = (current + step) /100;
}
else
{ // obj.style.filter = alpha(opacity = 30)
obj.style.filter = "alpha(opacity = "+(current + step)* 10+")";

}
}
else if(attr == "zIndex")
{
obj.style.zIndex = json[attr];
}
else
{
obj.style[attr] = current + step + "px" ;
}

if(current != json[attr]) // 只要其中一个不满足条件 就不应该停止定时器 这句一定遍历里面
{
flag = false;
}
}
if(flag) // 用于判断定时器的条件
{
clearInterval(obj.timer);
//alert("ok了");
if(fn) // 很简单 当定时器停止了。 动画就结束了 如果有回调,就应该执行回调
{
fn(); // 函数名 + () 调用函数 执行函数
}
}
},30)
}
function getStyle(obj,attr) { // 谁的 那个属性
if(obj.currentStyle) // ie 等
{
return obj.currentStyle[attr]; // 返回传递过来的某个属性
}
else
{
return window.getComputedStyle(obj,null)[attr]; // w3c 浏览器
}
}
</script>

看完了这篇文章,相信你对“原生JS封装animate运动框架的示例分析”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js
AI