易错点
- 几个物体几个独立的属性
function startMove(obj,iTarget){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var speed=(iTarget-obj.alpha)/6;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(iTarget==obj.alpha){
clearInterval(obj.timer);
}
else{
obj.alpha+=speed;
obj.style.opacity=obj.alpha/100;
}
},30);
}
timer和alpha在多个div中不能共用,即自己用自己最安全 - JS中offset系列的误区
- offsetWidth不一定等于style.width,比较:
<head>
<style>
#div1{
width:100px;
height:100px;
background:red;
}
</head>
第一种的offsetWidth与style.width值大小相等
第二种的offsetWidth与style.width值大小不相等
说明:offset系列大小=style.width+padding+border
运动控制函数startMove与解决第二个问题的getStyle函数
getStyle函数从非内嵌样式获取css样式
function getStyle(obj,name){
if(obj.currentStyle){
return obj.currentStyle[name];
}
else{
return getComputedStyle(obj,1)[name];
}
}
包打天下的startMove函数
function startMove(obj,attr,iTarget){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var cur=parseInt(getStyle(obj,attr));
var speed=(iTarget-cur)/6;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(iTarget==cur){
clearInterval(obj.timer);
}
else{
obj.style[attr]=cur+speed+'px';
}
},30);
}
去掉offset
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>去掉offset</title>
<style>
div{
float: left;
width: 150px;
height: 150px;
background: red;
margin-left: 20px;
border: 1px solid black;
}
</style>
<script>
window.onload=function(){
var oDiv1=document.getElementById('div1');
var oDiv2=document.getElementById('div2');
oDiv1.onmouseover=function(){
startMove(this,'width',300);
}
oDiv1.onmouseout=function(){
startMove(this,'width',150);
};
oDiv2.onmouseover=function(){
startMove(this,'height',300);
};
oDiv2.onmouseout=function(){
startMove(this,'height',150);
};
};
function getStyle(obj,name){
if(obj.currentStyle){
return obj.currentStyle[name];
}
else{
return getComputedStyle(obj,1)[name];
}
}
function startMove(obj,attr,iTarget){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var cur=parseInt(getStyle(obj,attr));
var speed=(iTarget-cur)/6;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(iTarget==cur){
clearInterval(obj.timer);
}
else{
obj.style[attr]=cur+speed+'px';
}
},30);
}
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>