123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- /* 清除默认样式 */
- * {
- margin: 0;
- padding: 0;
- }
- #box1 {
- width: 100px;
- height: 100px;
- background-color: red;
- position: absolute;
- /*
- 增加一个left:0,主要是解决部分IE浏览器不能正常获取box1的原始left值的问题
- */
- left: 0;
- }
- </style>
- <script>
- window.onload = function () {
- //获取box1
- var box1 = document.getElementById('box1');
- //获取btn01
- var btn01 = document.getElementById('btn01');
- //定义一个变量,用来保存定时器的标识
- var timer;
- //点击按钮以后,box1向右移动(left值增大)
- btn01.onclick = function () {
- /**
- * 每次点击按钮,都会打开一个定时器,如果连续点击按钮,
- * 会打开多个定时器,为了确保每次点击都只打开一个定时器,
- * 就需要在一进入单击响应函数时,先关闭上一个定时器,
- * 所以,也需要把定时器的标识设置为一个全局变量
- */
- //关闭上一个定时器
- clearInterval(timer);
- //开启定时器,用来执行动画效果
- timer = setInterval(function () {
- //获取box1的原来的left值
- var oldValue = parseInt(getStyle(box1, "left"));
- //在旧值的基础上增加
- var newValue = oldValue + 19;
- //判断newValue是否大于500
- if (newValue > 500) {
- newValue = 500;
- };
- //将新值设置给box1
- box1.style.left = newValue + 'px';
- //当元素移动到800px时,使其停止执行动画
- if (newValue == 500) {
- clearInterval(timer);
- };
- }, 30);
- };
- };
- function getStyle(obj, name) {
- if (window.getComputedStyle) {
- //正常浏览器的方式,具有getComputedStyle()方法
- return getComputedStyle(obj, null)[name];
- } else {
- //IE8的方式,没有getComputedStyle()方法
- return obj.currentStyle[name];
- };
- };
- </script>
- </head>
- <body>
- <button id="btn01">点击按钮以后box1向右移动</button>
- <br><br>
- <div id="box1"></div>
- <!-- 设置一条参考线,用来判断box1是否移动了想要的距离 -->
- <div style="width: 0;
- height: 1000px;
- border-left: 1px black solid;
- position: absolute;
- left: 500px;
- top: 0;"></div>
- </body>
- </html>
|