js动画---一个小bug的处理

2023-06-05,,

对于前面的课程,大家似乎看不出来存在什么问题,一切都很顺利,但是其实是存在一个很大的bug的,这个bug是什么呢??

我们来看看下面这个程序就知道了

<!DOCTYPE html>
<html>
<head>
<title>js动画事件</title>
<link href="move.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="move.js"></script>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>

css文件(这里面为元素添加了border边框值)

*{
margin:0px;
padding:0px;
}
li{
width:200px;
height:100px;
background-color:red;
margin-bottom:30px;
border:1px solid #eeddcc;//我们多添加了这一行,看看会出现什么问题。
}

js文件

window.onload=function(){
var ls=document.getElementsByTagName("li");
for(var i=0,l=ls.length;i<l;i++){
ls[i].timer=null;
ls[i].onmouseover=function(){
startMove(this,400);
}
ls[i].onmouseout=function(){
startMove(this,200);
}
}
}
function startMove(object,Target){
clearInterval(object.timer);
object.timer=setInterval(function(){
var speed;
if(Target==400){
speed=1;
}else{
speed=-1;
}
if(object.offsetWidth==Target){
clearInterval(object.timer);
}else{
object.style.width=object.offsetWidth+speed+"px";
}
},50)
}

大家觉得似乎没有什么问题啊?其实运行一下就会发现,宽度到达398px就停止了,然后我们离开时又会增加?

我们仔细分析一下,因为offsetWidth获得的值会包括边框,那么边框2厘米,所以width就398厘米,但是离开时又会增加是为什么呢?

当我们离开时speed就变成可-1,那么此时的object.style.width=object.offsetWidth(400)+speed(-1)=399px;

然后到下一次判断语句object.offsetWidth=object.style.width(上一次等于399px)+border(2px)=401px;所以继续执行,然后一直执行下去。

我们在来看一个例子

js2

window.onload=function(){
var ls=document.getElementsByTagName("li");
for(var i=0,l=ls.length;i<l;i++){
ls[i].timer=null;
ls[i].onmouseover=function(){
startMove(this);
} } }
var timer;
function startMove(object){
var speed=-1;
clearInterval(timer);
timer=setInterval(function(){
object.style.width=object.offsetWidth+speed+"px";
},50)
}

这里我们明明设置的speed=-1,照说应该会慢慢变短的,但是发现运行结果是慢慢变长,这是为什么呢??

这还是因为border的问题。为什么呢?

比如此时的object.style.width=object.offsetWidth(200)-1=199PX

然后下一刻object.offsetWidth=199+border(2px)=201;如此反复所以是一直在增加。

所以发现通过object.offsetWidth这个存在一个bug。那我们如何来修改呢

方法一,将width,height参数写到元素里面去

<li style="width:200px; height:100px"></li>

然后这样获取object.style.width=parseInt(object.style.width)+speed+"px";

方法二

运用getStyle函数来获取属性

在js中定义一个getStyle函数;

js文件

window.onload=function(){
var ls=document.getElementsByTagName("li");
for(var i=0,l=ls.length;i<l;i++){
ls[i].timer=null;
ls[i].onmouseover=function(){
startMove(this);
} } }
var timer;
function startMove(object){
var speed=-1;
clearInterval(timer);
timer=setInterval(function(){
object.style.width=parseInt(getStyle(object,"width"))+speed+"px";//parseInt不能丢。
},50)
}
function getStyle(object,attr){//自定义一个函数用来获取属性值
if(object.currentStyle){
return object.currentStyle[attr];//IE浏览器
}else if(getComputedStyle){
return getComputedStyle(object,false)[attr];//火狐浏览器
}
}

js动画---一个小bug的处理的相关教程结束。

《js动画---一个小bug的处理.doc》

下载本文的Word格式文档,以方便收藏与打印。