运动框架:1、在你点击开始时,一定要把之前所有的定时器关闭
2、把停止定时器和运动分开,使用(if/else)隔开
js运动基础一:匀速运动
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>运动基础一</title>
<style>
#div1{width: 200px;height: 200px;background-color: #0000FF;position: absolute;left: 0;}
</style>
<script>
window.onload=function(){
var div1 = document.getElementById('div1');
var btn1 = document.getElementById('btn1');
var time ='';
btn1.onclick=function(){
//为了防止点击会进行加速,因为每点击一次会开一个定时器,所以要清除所有的定时器
clearInterval(time);
time = setInterval(function(){
var speed=10;
//判断句中要写成大于300,因为如果写等于300,因为speed不是一个像素的加起来的
//如果此时的值刚好跳过300的时候,还是会一直运动
if(div1.offsetLeft>300){
clearInterval(time);
}else{
//一定要把下面这句话放到else中,
//因为如果不放的话,每当点击的时候图片还是会移动speed的位移
div1.style.left = div1.offsetLeft+speed+'px';
}
},30);
}
}
</script>
</head>
<body>
<input id='btn1' type="button" value="点击开始" />
<div id='div1'>
</div>
</body>
</html>
分享到案例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js运动分享到</title>
<style>
#div1{width: 100px; height: 200px;background-color: #0000FF;position: absolute;left: -100px;}
span{width: 30px;height: 100px;position: absolute;right: -30px;top:50px;
background-color: green;line-height: 30px;text-align:center;}
</style>
<script>
window.onload=function(){
var oDiv = document.getElementById('div1');
oDiv.onmouseover=function(){
startMove(0);
}
oDiv.onmouseout=function(){
startMove(-100);
}
//为了简便代码,所以把形同的部分作为参数传进去
function startMove(target){
var time='';
var speed=0;
var oDiv = document.getElementById('div1');
clearInterval(time);
time = setInterval(function(){
if(oDiv.offsetLeft>target){
speed = -2;
}else{
speed = 2;
}
if(oDiv.offsetLeft==target){
clearInterval(time);
}else{
oDiv.style.left = oDiv.offsetLeft+speed+'px';
}
},10);
}
}
</script>
</head>
<body>
<div id='div1'>
<span>分享到</span>
</div>
</body>
</html>
图片淡入淡出效果
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片淡入淡出效果</title>
<style>
img{ width:250px;height: 150px; filter:alpha(opacity:30);opacity: 0.3;}
</style>
<script>
window.onload=function(){
var img1 = document.getElementById('img1');
img1.onmouseover=function(){
startMove(100);
}
img1.onmouseout=function(){
startMove(30);
}
}
//对于这个变量,要放到外面,不然效果会出现错误
var alpha = 30;
var time = '';
function startMove(target){
var img1 = document.getElementById('img1');
var speed=0;
clearInterval(time);
time = setInterval(function(){
if(alpha>target){
speed=-5;
}else{
speed=5;
}
if(alpha==target){
clearInterval(time);
}else{
alpha+=speed;
img1.style.filter='alpha(opacity:'+alpha+')';
img1.style.opacity = alpha/100;
}
},30);
}
</script>
</head>
<body>
<div id='div1'>
<img id='img1' src="../img/3.jpg">
</div>
</body>
</html>