js动画(3)——缓冲动画
2016-02-18 22:21
603 查看
<pre name="code" class="html"><!DOCTYPE = html> <html> <head> <title></title> <style> body{ margin: 0px; padding: 0px; } .red{ background-color:red; width:200px; height:200px; position:relative; left:-200px; top:0px; } .blue{ background:blue; width:20px; height:50px; position:absolute; left:200px; top:75px; } </style> <script src="file:///F:front end/jquery/jquery-1.11.3.min.js"></script> </head> <body> <div class="red" id="cf1"><div class="blue" id="cf">分享</div></div> <script> window.onload = function(){ var onDiv = document.getElementById("cf1"); onDiv.onmouseover = function(){ startmove(0); } onDiv.onmouseout = function(){ startmove(-200); } } var timer ; function startmove(target){ clearInterval(timer);//清除定时器,以免多次触发定时器导致速度越来越快而不是匀速前进 var onDiv1 = document.getElementById("cf1"); timer = setInterval(function(){ var speed = (target-onDiv1.offsetLeft)/10; speed = speed>0?Math.ceil(speed):Math.floor(speed);//避免当不为整数个像素时,无法移动出现误差的情况 if(onDiv1.offsetLeft==target){ clearInterval(timer); } // speed = Math.floor(speed); else{ onDiv1.style.left = onDiv1.offsetLeft+speed+'px'; } },30) } </script> </body> </html>
小结:
1、这个例子和第一个例子很类似,区别在于速度的变化(越接近目标速度越低);
2、由于速度在设置时已经确定了符号,所以不用分情况讨论;
3、为啥speed大于0时向上取整,小于0时候向下取整,要想清楚。
相关文章推荐
- Web布局连载——两栏固定布局(五)
- [div+css]晒晒最新制作专题推广页模板
- 异步流程控制:7 行代码学会 co 模块
- [译] React 入门
- 如何优雅处理前端异常?
- 设计更快的网页(三):字体和 CSS 调整
- 纯CSS制作的新闻网站中的文章列表
- 10条影响CSS渲染速度的写法与使用建议第1/3页
- BS项目中的CSS架构_仅加载自己需要的CSS
- 很不错的 CSS Hack 又学了一招
- 发一个css比较清爽的写法
- CSS expression控制图片自动缩放效果代码[兼容 IE,Firefox]
- css布局网页水平居中常用方法
- CSS经典技巧十则第1/2页
- css 兼容性问题this.style.cursor=''hand''
- IE6不能正常解析CSS文件问题的解决方法及原因分析
- 欲练CSS ,必先解决IE的一些细节分析
- CSS文字截取功能实现代码
- 支持IE6 IE7 Firefox 的纯CSS的下拉菜单