两个物体一个变宽,一个变高
offsetWidth:得到的是盒模型值,对于盒模型尺寸,需要考虑的就有很多,比如padding以及border.
所以下面的案例中,width本身为200,设一个宽度为1的边框后,offsetwidth就会变为202,每执行一次,虽然会减一,此时把得到的值赋给width,width此时就为201,以此类推,width是增加的。
与此同时,因为需要改变的仅仅是width和height两个参数,因此可以利用[name]获取属性的方法来,把width和height作为参数传进去。此时就可以简化代码。
这样就获得了可以穿任意值和属性的方法,但是不适用opacity,即不适合透明度,因为当我们对在对获取到的属性值会进行一个parseInt的处理,而透明度是小数。此时用if判断,是opacity就使用parseFloat()*100;但是对于计算机来存储小数的时候,比如0.7*100就会变成7.0000000001,所以要对得到的结果进行四舍五入,此时用到Math.round();
这个时候需要另外就是在赋值的时候,透明度不用加px。解决办法就是,在框架里进行if判断,如果是opacity,就使用一种另一种办法。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>两物体不同的运动</title>
<style>
#div1{width: 200px;height: 200px;background-color: blue;float: left;}
#div2{width: 200px;height: 200px;background-color: #DB7093;float: left;font-size: 12px;}
#div3{width: 200px;height: 200px;background-color: blue;float: left;border:1px solid aquamarine;}
#div4{width: 200px;height: 200px;background-color: blue;float: left;filter: alpha(opacity: 30);opacity: 0.3;}
</style>
<script>
window.onload=function(){
var oDiv1 = document.getElementById('div1');
var oDiv2 = document.getElementById('div2');
var oDiv3 = document.getElementById('div3');
var oDiv4 = document.getElementById('div4');
oDiv1.onmouseover=function(){
startMove(this,'height',400);
}
oDiv1.onmouseout=function(){
startMove(this,'height',200);
}
oDiv2.onmouseover=function(){
startMove(this,'font-size',50);
}
oDiv2.onmouseout=function(){
startMove(this,'font-size',12);
}
oDiv3.onmouseover=function(){
startMove(this,'borderWidth',100);
}
oDiv3.onmouseout=function(){
startMove(this,'borderWidth',10);
}
oDiv4.onmouseover=function(){
startMove(this,'opacity',100);
}
oDiv4.onmouseout=function(){
startMove(this,'opacity',30);
}
}
//封装一个函数,解决对于offset出现的bug,因为利用这种方法这样获得的就是物体真正的宽度或者高度
//而offset获得的是盒模型后的值
function getStyle(obj,name){
if(obj.currentStyle){
return obj.currentStyle[name];
}else{
return getComputedStyle(obj,false)[name];
}
}
function startMove(obj,attr,target){
clearInterval(obj.time);
obj.time=setInterval(function(){
//此时,可以使用之前封装好的函数,但是一定要记得使用parseInt,
//因为得到的值带有px,使用parseInt把他转化为整数
//对于透明度要换一种方式
var curr=0;
if(attr=='opacity'){
//计算机存储小数时出现的bug,0.07*100得到的是7.000000001,所以四舍五入
curr = Math.round(parseFloat(getStyle(obj,attr))*100);
}else{
curr = parseInt(getStyle(obj,attr));
}
var speed = (target-curr)/6;
speed = speed>0?Math.ceil(speed):Math.floor(speed);
//此时不需要使用>号,是因为对于缓冲运动而言,速度是变化的,到最后的时候,速度回变成1
//因此不会存在高度大于目标值的情况
if(curr==target){
clearInterval(obj.time);
}else{
//此时可以利用[]获取属性的方法把属性作为参数传进来,
//即把obj.style.height 转换为obj.style['height']
if(attr=='opacity'){
//记得加括号
obj.style.filter = 'alpha(opacity:'+(curr+speed)+')';
obj.style.opacity = (curr+speed)/100;
}else{
obj.style[attr] = curr+speed+'px';
}
}
},30)
}
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2">很开心你终于来了,在我差一点放弃的时刻</div>
<div id="div3"></div>
<div id="div4"></div>
</body>
</html>