1. 程式人生 > >運動模組1

運動模組1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>移動案例</title>
    <style>
        .box{
            width: 100px;
            height: 100px;
            background-color: green;
            position: absolute;
            top: 100
px; } </style> </head> <body> <input type="button" value="移動到400px" id="btn1"> <input type="button" value="移動到800px" id="btn2"> <br> <div class="box" id="dv"></div> <script> function $(id) { return document.getElementById(id) }
//運動框架 function animate(ele,target,step) { let s = step //把當前的步數進行記錄 //先清理定時器 clearInterval(ele.timer) ele.timer = setInterval(function () { //ele是一個物件,把定時器的變數變為一個物件的屬性 //獲取當前的div的位置 var current = ele.offsetLeft; //div移動的步數 //判斷是從左或從右走
step = current<target?s:-s;//當前的距離小於目標值時,需要為正的步數,否則為負數 //每次移動後的距離 current+= step; //判斷當前移動後的位置是否到達目標位置 if(Math.abs(target-current)>Math.abs(step)){ //當為負數時,有絕對值比較數字 ele.style.left = current+'px';//當大於步數時,說明還有距離 }else{ clearInterval(ele.timer) ele.style.left = target+'px'; //當小於步數時,說明當時已經接近目標,就直接讓他到目標位置 } },20) } $('btn1').onclick = function () { animate($('dv'),400,10) }; $('btn2').onclick = function () { animate($('dv'),800,10) } function Move(left,step,ele) { var current = ele.offsetLeft; //獲取當前的位置 current +=step; if(current<=left){ ele.style.left = current+'px'; }else{ return; } } //勻速前進,最終移到400px, // var timer = null; //只產生一個定時器 // $('btn1').onclick = function () { // setInterval(function() { // Move(400,10,$('dv')) // }, 20) // // //setInterval(Move(400,10),20) // } // $('btn2').onclick = function () { // setInterval(function () { // Move(800,10,$('dv')) // },20) // } </script> </body> </html>