时间:2021-07-01 10:21:17 帮助过:4人阅读
//鼠标移到元素上元素右移,鼠标离开元素回去。
var timer="";
function Move(speed,locat) {//移动速度,移动终点位置
var ob=document.getElementById('box1');
clearInterval(timer);//先清除定时器,防止定时器的嵌套调用
timer=setInterval(function () {
if (ob.offsetLeft==locat) {//当前位置到达指定终点,关闭定时器
clearInterval(timer);
} else {//否则元素的left属性等于当前left加上每次改变的速度
ob.style.left=ob.offsetLeft+speed+'px';
}
}, 30)
}举个栗子:
在下面的HTML文档中调用上面的JS函数
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#box1{
width: 200px;
height: 200px;
background-color: red;
position: absolute;
left: 0;
}
</style><div id="box1"></div>
<script type="text/javascript">
window.onload=function(){
var ob=document.getElementById('box1');
ob.onmouseover=function(){
Move(10,200);//鼠标移到div上时div从0移到200
}
ob.onmouseout=function(){
Move(-10,0);//鼠标移走时div从200移到0
}
}
</script>三、简单动画之改变透明度
函数的模型和上一节基本一致,不同的是元素没有自身透明度属性,需要先把透明度初值定义好。
1 var timer="";
2 var alpha=30;//透明度初始值
3 function changeOpacity(speed,target) {
4 var div1=document.getElementById('div1');//获取改变透明度的元素
5 clearInterval(timer);//清除定时器,避免嵌套调用
6 timer=setInterval(function () {
7 if (alpha==target) {//如果透明度达到目标值,清除定时器
8 clearInterval(timer);
9 } else {//当前透明度加上透明度变化的速度
10 alpha=alpha+speed;
11 div1.style.filter='alpha(opacity:'+alpha+')';//IE浏览器
12 div1.style.opacity=alpha/100; //火狐和谷歌
13 }
14 }, 30)
15 }在下面的HTML文档中引用上面的JS函数,实现透明度的改变
1 <style type="text/css">
2 *{
3 margin: 0;
4 padding: 0;
5 }
6 #div1{
7 width: 200px;
8 height: 200px;
9 background: red;
10 filter: alpha(opacity:30);/*filter滤镜:不透明度,IE浏览器*/
11 opacity: 0.3;/*火狐和谷歌*/
12 }
13 </style>1 <div id="div1"></div>
2 <script type="text/javascript">
3 window.onload=function(){
4 var div1=document.getElementById('div1');
5 div1.onmouseover=function(){
6 changeOpacity(10,100);
7 }
8 div1.onmouseout=function(){
9 changeOpacity(-10,30);
10 }
11 }以上就是js动画学习(一)的内容,更多相关内容请关注PHP中文网(www.gxlcms.com)!