登录  /  注册
首页 > web前端 > js教程 > 正文

JS封装animate运动框架的实例详解

小云云
发布: 2018-01-24 15:48:43
原创
1346人浏览过

本文主要为大家带来一篇原生js封装animate运动框架的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望能帮助到大家。

如下所示:


<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
p {
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>
<p id="box"></p>
</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实现jQuery的animate()动画

jquery animate动画持续运动的实例

css动画制作——CSS animate

以上就是JS封装animate运动框架的实例详解的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号