qq_独为伊人醉_2
2018-06-01 16:11
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>分享</title>
<style type="text/css">
* {
padding: 0;
margin: 0;
}
#div1 {
width: 200px;
height: 200px;
background-color: red;
position: relative;
left: -200px;
top: 0;
}
#div1 span {
width: 20px;
height: 50px;
background-color: blue;
position: absolute;
left: 200px;
top: 75px;
}
</style>
<script type="text/javascript">
window.onload = function() {
var oDiv = document.getElementById("div1"); //oDiv是局部变量,只在此函数内有效
//鼠标移入事件
oDiv.onmouseover = function() {
starMove(0);
}
//鼠标移出事件
oDiv.onmouseout = function() {
starMove(-200);
}
var timer = null;
function starMove(target) {
clearInterval(timer);//解决“speed”的叠加问题
var oDiv = document.getElementById("div1");
//创建一个定时器timer
timer = setInterval(function() {
var speed = (target-oDiv.offsetLeft)/20;
speed = speed>0?Math.ceil(speed):Math.floor(speed);
if(oDiv.offsetLeft == target) {
clearInterval(timer);
//符合条件运动停止
} else {
oDiv.style.left = oDiv.offsetLeft + speed + 'px';
}
}, 30);
}
}
</script>
</head>
<body>
<div id=div1>
<span>分享</span>
</div>
</body>
</html>
id="div1" 没有加引号
JS动画效果
113920 学习 · 1500 问题