<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>匀速动画</title>
<style type="text/css">
#move{
width: 200px;
height: 200px;
background-color: #996666;
position: absolute;
top: 20px;
left: -190px;
cursor:pointer;
}
</style>
<script type="text/javascript">
window.onload=function(){
var getp = document.getElementById('move');
getp.onmouseover = function(){
startMove();
}
getp.onmouseout = function(){
moveBack();
}
var timer = null;
function startMove(){
clearInterval(timer);
timer = setInterval(function(){
if(getp.offsetLeft==0){
clearInterval(timer);
}
else{
getp.style.left= getp.offsetLeft+10+"px";
}
},1);
}
function moveBack(){
clearInterval(timer);
timer = setInterval(function(){
if(getp.offsetLeft==-190){
clearInterval(timer);
}
else{
getp.style.left= getp.offsetLeft-1+"px";
}
},1);
}
}
</script>
</head>
<body>
<p id="move">
</p>
</body>
</html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这么简单的效果,直接用css写不是更好么
至于乱动,具体操作是先完全弹出来,然后p缓慢缩回去时再次把鼠标放在p上触发mouseover,是因为onmouseout中定时器的间隔比onmouseover定时器的移动距离小,要改的话,可以设置一个状态,等完全缩进去的时候onmouseover再允许定义定时器