js运动原理2
2016-05-09 08:56
447 查看
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#div1{
width: 100px;
height: 100px;
background: red;
position:absolute;
top: 50px;
left:0;
}
#div2{
width: 100px;
height: 100px;
background: red;
position:absolute;
top: 250px;
left:600px;
}
</style>
</head>
<body>
<input id="bt1" type="button" value="开始向右">
<input id="bt2" type="button" value="开始向左">
<div id="div1"></div>
<script type="text/javascript">
var oBt2=document.getElementById("bt2");
var oDiv1Timerid=null;
var oBt=document.getElementById("bt1");
oBt.onclick= function () {
var oDiv=document.getElementById("div1");
clearInterval(oDiv1Timerid); //1. 启动定时器之前,需要清理之前的定时器。
oDiv1Timerid=setInterval(function(){//启动定时器,并记录返回值(定时器的标识)
//做运动的部分 和 清理定时器的部分, 放在 if else 里面
if(oDiv.offsetLeft>600){
//清理定时器的 条件 。要注意边界判断!
clearInterval(oDiv1Timerid);
}
else{
oDiv.style.left=oDiv.offsetLeft+9+"px";
}
},30);
}
oBt2.onclick= function () {
var oDiv=document.getElementById("div1");
clearInterval(oDiv1Timerid);
oDiv1Timerid=setInterval(function(){
if(oDiv.offsetLeft<0){
clearInterval(oDiv1Timerid);
}
else{
oDiv.style.left=oDiv.offsetLeft-9+"px";
}
},30);
}
</script>
</body>
</html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#div1{
width: 100px;
height: 100px;
background: red;
position:absolute;
top: 50px;
left:0;
}
#div2{
width: 100px;
height: 100px;
background: red;
position:absolute;
top: 250px;
left:600px;
}
</style>
</head>
<body>
<input id="bt1" type="button" value="开始向右">
<input id="bt2" type="button" value="开始向左">
<div id="div1"></div>
<script type="text/javascript">
var oBt2=document.getElementById("bt2");
var oDiv1Timerid=null;
var oBt=document.getElementById("bt1");
oBt.onclick= function () {
var oDiv=document.getElementById("div1");
clearInterval(oDiv1Timerid); //1. 启动定时器之前,需要清理之前的定时器。
oDiv1Timerid=setInterval(function(){//启动定时器,并记录返回值(定时器的标识)
//做运动的部分 和 清理定时器的部分, 放在 if else 里面
if(oDiv.offsetLeft>600){
//清理定时器的 条件 。要注意边界判断!
clearInterval(oDiv1Timerid);
}
else{
oDiv.style.left=oDiv.offsetLeft+9+"px";
}
},30);
}
oBt2.onclick= function () {
var oDiv=document.getElementById("div1");
clearInterval(oDiv1Timerid);
oDiv1Timerid=setInterval(function(){
if(oDiv.offsetLeft<0){
clearInterval(oDiv1Timerid);
}
else{
oDiv.style.left=oDiv.offsetLeft-9+"px";
}
},30);
}
</script>
</body>
</html>
相关文章推荐
- js运动原理
- 关于xml和Json数据解析的一些总结
- js实际应用之一:密码加密
- JavaScript语句
- 江苏省大学生程序设计竞赛(JSCPC)赛后感
- JS 密码加密
- 前端开发之旅-JavaScript入门篇
- 前端开发-JavaScript入门 DOM篇
- 前端开发-JavaScript进阶篇
- web报jsp不能编译
- javascript组合继承
- JavaScript闭包
- ExtJS的内置校验vtype
- JS控制页面表格内数据,按照条件排序
- Ember.js 上手教程
- 开关门js
- ajax跨域调用webservice
- beego下ie提示下载json
- js实现跨域(jsonp, iframe+window.name, iframe+window.domain, iframe+window.postMessage)
- JS 中 new 操作符