物体运动、匀速运动
物体运动:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#div1 {
width: 200px;
height: 200px;
background: yellow;
position: absolute;
top: 50px;
left: 50px;
}
</style>
<script type="text/javascript">
var timer = null;
function startMove (){
var oBtn = document.getElementById('btn1');
var oDiv = document.getElementById('div1');
var speed = 1;
timer = setInterval(function(){
oDiv.style.left = oDiv.offsetLeft + speed +'px';
},30);
}
</script>
</head>
<body>
<input id="btn1" type="button" value="开始" onclick="startMove()" />
<div id="div1"></div>
</body>
</html>
当每点击按钮,物体的运动速度就会加快一倍,物体运动不会停止,一直运动下去;
匀速运动
var timer = null;
function startMove (){
var oBtn = document.getElementById('btn1');
var oDiv = document.getElementById('div1');
clearInterval(timer)
timer = setInterval(function(){
var speed = 1;
if (oDiv.offsetLeft >= 300) {
clearInterval(timer);
} else{
oDiv.style.left = oDiv.offsetLeft + speed +'px';
}
},30);
}
运动框架:
1、在开始运动时,关闭原有的定时器;
2、把运动和停止定时器分开(if/else);
典例:
多数网页上“分享到”的一栏
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#div1 {
width: 150px;
height: 200px;
background: green;
position: absolute;
left: -150px;
}
#div1 span {
position: absolute;
width: 20px;
height: 60px;
line-height: 20px;
background: blue;
right: -20px;
top: 70px;
}
</style>
<script type="text/javascript">
window.onload = function (){
var oDiv = document.getElementById('div1');
oDiv.onmouseover = function(){
startMove(0);
}
oDiv.onmouseout = function(){
startMove(-150);
}
}
var timer = null;
function startMove(iTarget){
var oDiv = document.getElementById('div1');
clearInterval(timer);
timer = setInterval(function(){
var speed = 0;
if (oDiv.offsetLeft>iTarget) {
speed = -10;
} else{
speed = 10;
}
if (oDiv.offsetLeft == iTarget) {
clearInterval(timer);
} else {
oDiv.style.left = oDiv.offsetLeft + speed + 'px';
}
}, 30);
}
</script>
</head>
<body>
<div id="div1">
<span>分享到</span>
</div>
</body>
</html>
鼠标移入移出都会运动
淡入淡出的图片
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#div1 {
width: 200px;
height: 200px;
background: red;
filter:alpha(opacity: 30); opacity: 0.3;
}
</style>
<script type="text/javascript">
window.onload = function(){
var oDiv = document.getElementById('div1');
oDiv.onmouseover = function (){
startMove(100);
}
oDiv.onmouseout = function(){
startMove (30);
}
}
var alpha = 30;
var timer = null;
function startMove(iTarget){
var oDiv = document.getElementById('div1');
clearInterval(timer);
timer = setInterval(function (){
var speed = 0;
if (alpha < iTarget) {
speed = 10;
} else {
speed = -10;
}
if (alpha == iTarget) {
clearInterval(timer);
} else {
alpha += speed;
oDiv.style.filter = 'alpha(opacity:'+alpha+')';
oDiv.style.opacity = alpha/100;
}
}, 30);
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
alpha只能用变量作为参数