<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#happy{
width: 200px;
height:200px;
border: 2px solid red;
filter:alpha(opacity:30);
opacity:0.3;
background-color: #3a2a45;
}
</style>
</head>
<body>
<div id="happy"></div>
<script>
//封装好的函数,获取样式style(解决offset样式的bug)
function getStyle(obj, attr) {
if (obj.currentStyle) { //IE浏览器
return obj.currentStyle[attr]
} else { //Chrome浏览器
return getComputedStyle(obj, false)[attr]
}
}
//动画函数,直接调用即可
function startMove(obj, json,fn) {
var all = true; //假设所有运动到达目标值
clearInterval(obj.timer);
obj.timer = setInterval(function () {
for(var attr in json){ //遍历取出json里的值
//通过in操作符,取得当前的属性值
var value = 0;
if (attr === 'opacity') {
value = Math.round(parseInt(getStyle(obj, attr)) * 100)
} else {
value = parseInt(getStyle(obj, attr));
}
//计算速度
var speed = (json[attr] - value) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (value !== json[attr] ) {
all =false;
}
if (attr === 'opacity') {
obj.style.filter = 'alpha:(opacity:' + value + speed + ')';
obj.style.opacity = (value + speed) / 100;
} else {
obj.style[attr] = value + speed + 'px';
}
}
if(all){
clearInterval(obj.timer);
if(fn){
fn()
}
}
}, 30)
}
</script>
<script>
window.οnlοad=function () {
var happy=document.getElementById('happy');
happy.οnmοuseοver=function () {
startMove(happy,{width:500,height:350,opacity:200})
};
happy.οnmοuseοut=function () {
startMove(happy,{width:200,height:200,opacity:50})
};
};
</script>
</body>
</html>
原生js方法:
封装好的js文件,只需调用startMove(obj,json,fn)这个函数
三个参数分别为:第一个:对象,id或者class等,第二个:json为属性值,
如width:200px,height:150px;可同时改变多个值;
fn为回调函数,执行其他的事情。
另外有特简洁的jQuery方法:4行代码可实现同样效果。。。
$(function () {
$("#id").mouseenter(function () {
$(this).animate({top: '25px', opacity: '30'}, 300, function () {
$(this).css({width: "30px"});
$(this).animate({top: '0', opacity: '10'}, 200)
})
})
});