javascript——运动函数.doc

javascript——运动函数   除了拖拽以外,运动也是javascript动画的一个基本操作。通过CSS属性transition和animation可以实现运动。但是,要进行更精细地操作,javascript运动是必不可少的。本文将详细介绍javascript运动 简单运动   让一个元素在页面中运动起来很简单,设置定时器,改变定位元素的left或top值即可 复制代码 button id=btn开始运动/button button id=reset还原/button div id=test style=height: 100px;width: 100px;background-color: pink;position:absolute;left:0;/div script var timer; reset.onclick = function(){history.go();} btn.onclick = function(){ timer = setInterval(function(){ if(test.offsetLeft 500){ test.style.left = test.offsetLeft + 10 + px; }else{ test.style.left = 500px; clearInterval(timer); } },30); } /script 复制代码 定时器管理   上面的代码中没有进行定时器管理。当元素在运动的过程中,多次按下按钮,但会开启多个定时器,从而使元素运动速度加快   有两种定时器管理方式 【1】开启新定时器前,消除旧定时器   [注意]即使没有定时器的情况下,消除定时器也不会报错,只是静默失败 复制代码 button id=btn开始运动/button button id=reset还原/button div id=test style=height: 100px;width: 100px;background-color: pink;position:absolute;left:0;/div script var timer; reset.onclick = function(){history.go();} btn.onclick = function(){ clearInterval(timer); timer = setInterval(function(){ if(test.offsetLeft 500){ test.style.left = test.offsetLeft + 10 + px; }else{ test.style.left = 500px; clearInterval(timer); } },30); } /script 复制代码 【2】当定时器未停止时,不允许开启新定时器   [注意]由于定时器开启时,其返回值是一个不为0的整数,所以可以通过判断其返回值,来确定是否使用return语句 复制代码 button id=btn开始运动/button button id=reset还原/button div id=test style=height: 100px;width: 100px;background-color: pink;position:absolute;left:0;/div script var timer; reset.onclick = function(){history.go();} btn.onclick = function(){ if(timer) return; timer = setInterval(function(){ if(test.offsetLeft 500){ test.style.left = test.offsetLeft + 10 + px; }else{ test.style.left = 500px; clearInterval(timer); } },30); } /script 复制代码 “分享”效果   现在要做一个类似于“分享到”侧边栏的效果 复制代码 style #test{

文档评论(0)

1亿VIP精品文档

相关文档