<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div{
width:200px;
height:200px;
border:2px solid red;
margin:10px;
background-color: green;
opacity:0.3;
font-size: 14px;
filter:alpha(opacity:30);
}
</style>
</head>
<body>
<div> 变宽</div>
<div>变高</div>
<div>fhhfshdjsd</div>
<script>
window.onload=function(){
var div=document.getElementsByTagName('div');
div[0].onmouseover=function(){
// startMove(this,'opacity',100);
startMove(this,'width',500);
//同一个函数调用两次 前一个会被覆盖
}
div[1].onmouseover=function(){
startMove(this,'height',900);
// console.log(this.style.height);
}
div[2].onmouseover=function(){
startMove(this,'fontSize',20);
}
}
function getStyle(obj,name){//获取样式
if(obj.currentStyle){
return obj.currentStyle[name];
}else{
return getComputedStyle(obj,null)[name];
}
}
// var timer=null;
function startMove(obj,name,target){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var curr=0;//存贮获取样式的值
if(name=='opacity'){
curr=Math.round(parseFloat(getStyle(obj,name))*100);
//Math.round解决小数问题
}else{
curr=parseInt(getStyle(obj,name));
}
var speed=(target-curr)/6;//目标地址和当前地址不能写反
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(curr==target){
clearInterval(obj.timer);
}else{
if(name=='opacity'){
curr=curr+speed;
obj.style.filter='alpha(opacity:+'+curr+')';
obj.style.opacity=curr/100;
// console.log(curr);
}else{
obj.style[name]=curr+speed+'px';
}
}
},300);
}
</script>
</body>
</html>