网站首页 > 技术文章 正文
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta charset="UTF-8">
<title>方块匀速运动</title>
<style type="text/css">
#box{
width:200px;
height:200px;
background-color :red;
margin-top:50px;
}
</style>
</head>
<script type="text/javascript">
var leftmargin=0, timer;
function run(){
window.clearInterval(timer); //清除定时器
timer = self.setInterval("move(7,300)",50);//使用定时器,每隔50毫秒调用1次move()方法
}
//moveMargin:向右移动单位值;stopMargin:停止移动的值。
function move(moveMargin,stopMargin){
//当(停止移动的值-已移动的值)的绝对值<向右移动的值时,将停止移动的值赋给目前需移动的值,否则目前已移动的值加上向右移动单位值赋给目前需移动的值
leftmargin = Math.abs(stopMargin-leftmargin<moveMargin) ? stopMargin : leftmargin + moveMargin;
document.getElementById('box').style.marginLeft = leftmargin + "px";
if(leftmargin == stopMargin){
//去掉定时器的方法
window.clearInterval(timer);
leftmargin=0;
}
}
</script>
<body>
<button onclick="run()"> run</button>
<div id="box" >
</div>
</body>
</html>
猜你喜欢
- 2024-09-21 从案例中学习JavaScript,超简单函数封装技巧
- 2024-09-21 如何使用 JavaScript 快速构建一个二维码生成器-web前端技术
- 2024-09-21 登顶GitHub趋势榜,标星1.8k:200行JS代码让画面人物瞬间消失
- 2024-09-21 JS,WebGL第三方库Three.js,三大基本对象:场景、相机和渲染器
- 2024-09-21 css面试题6: 如何理解margin重叠问题
- 2024-09-21 解读 CSS 布局之水平垂直居中(css设置水平垂直居中)
- 2024-09-21 手撕代码--JavaScript实现年历(手撕代码什么意思)
- 2024-09-21 Three.JS教程1环境搭建、场景与相机
- 2024-09-21 在网页开发中,我们需要掌握的常用HTML标签有哪些?
- 2024-09-21 探秘 flex 上下文中神奇的自动 margin,干货!网友都感动哭了
- 最近发表
- 标签列表
-
- cmd/c (90)
- c++中::是什么意思 (84)
- 标签用于 (71)
- 主键只能有一个吗 (77)
- c#console.writeline不显示 (95)
- pythoncase语句 (88)
- es6includes (74)
- sqlset (76)
- apt-getinstall-y (100)
- node_modules怎么生成 (87)
- chromepost (71)
- flexdirection (73)
- c++int转char (80)
- mysqlany_value (79)
- static函数和普通函数 (84)
- el-date-picker开始日期早于结束日期 (76)
- js判断是否是json字符串 (75)
- c语言min函数头文件 (77)
- asynccallback (87)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- java (73)
- js数组插入 (83)
- mac安装java (72)
- 无效的列索引 (74)