<html xmlns="
<head>
<meta http-equiv="Content-Type" content="text/html charset=utf-8" />
<title>test</title>
<style>
#div1 {
width:100px
height:100px
background:#f93
position:absolute
left:200px
top:200px
}
#div2 {
width:100px
height:100px
background:#f00
position:absolute
left:200px
top:400px
-webkit-transition:all 1s linear
-moz-transition:all 1s linear
-ms-transition:all 1s linear
-o-transition:all 1s linear
transition:all 1s linear
}
#div2:hover{
-webkit-transform: scale(2,2)
-moz-transform: scale(2,2)
-ms-transform: scale(2,2)
-o-transform: scale(2,2)
transform: scale(2,2)
}
</style>
<script>
window.onload = function(){
var oDiv = document.getElementById('div1')
oDiv.onmouseover = function(){
startMove(oDiv,{width:200, height:200, marginLeft:-50, marginTop:-50})
}
oDiv.onmouseout = function(){
startMove(oDiv,{width:100, height:100, marginLeft:0, marginTop:0})
}
}
function getStyle(obj,attr){
return obj.currentStyle? obj.currentStyle[attr]: getComputedStyle(obj)[attr]
}
function startMove(obj,json,endFn){
clearInterval(obj.timer)
obj.timer = setInterval(function(){
var onOff = true
for(var attr in json){
//1.取当前值
var iCur = 0
if(attr == 'opacity'){
iCur = parseInt(parseFloat(getStyle(obj,attr)) * 100)
}
else{
iCur = parseInt(getStyle(obj,attr))
}
//2.计算速度
var speed = (json[attr] - iCur)/8
speed = speed>0 ? Math.ceil(speed) : Math.floor(speed)
//判断是否到达终点
if(iCur !== json[attr]){
onOff = false
if(attr == 'opacity' ){
obj.style.opacity = (iCur + speed)/100
obj.style.filter = 'alpha(opacity=' + (iCur + speed) + ')'
}else{
obj.style[attr] = (iCur + speed) + 'px'
}
}
}
if(onOff){
clearInterval(obj.timer)
endFn && endFn()
}
},30)
}
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
赞同用css3实现,比js更方便简洁,可以看下这个代码,我做了个红色的,纯ccs实现这个效果
if(oDiv.offsetTop==itarget){clearInterval(timer)} 这里,oDiv.offsetTop和itarget相等的几率是很小的,所以会导致后来一直抖动