亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JS div勻速移動動畫與變速移動動畫代碼實例

 更新時間:2019年03月26日 08:43:34   作者:夏沐_lk  
這篇文章主要介紹了JS div勻速移動動畫與變速移動動畫,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

1.勻速移動代碼

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>title</title>
 <style>
  * {
   margin: 0;
   padding: 0;
  }
 
  div {
   margin-top: 20px;
   width: 200px;
   height: 100px;
   background-color: green;
   position: absolute;
   left: 0;
   top: 0;
  }
 </style>
</head>
<body>
<input type="button" value="移動到400px" id="btn1"/>
<input type="button" value="移動到800px" id="btn2"/>
<div id="dv">
 <script src="common.js"></script>
 <script>
  //點擊按鈕移動div
 
  my$("btn1").onclick = function () {
   animate(my$("dv"), 400);
  };
  my$("btn2").onclick = function () {
   animate(my$("dv"), 800);
  };
 
  //勻速動畫
  function animate(element, target) {
   //清理定時器
   clearInterval(element.timeId);
   element.timeId = setInterval(function () {
    //獲取元素的當(dāng)前位置
    var current = element.offsetLeft;
    //移動的步數(shù)
    var step = 10;
    step = target > current ? step : -step;
    current += step;
    if (Math.abs(current - target) > Math.abs(step)) {
     element.style.left = current + "px";
    } else {
     clearInterval(element.timeId);
     element.style.left = target + "px";
    }
   }, 20);
  }
 </script>
</div>
</body>
</html>

2.變速移動代碼

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>title</title>
 <style>
  * {
   margin: 0;
   padding: 0;
  }
 
  div {
   margin-top: 20px;
   width: 200px;
   height: 100px;
   background-color: green;
   position: absolute;
   left: 0;
   top: 0;
  }
 </style>
</head>
<body>
<input type="button" value="移動到400px" id="btn1"/>
<input type="button" value="移動到800px" id="btn2"/>
<div id="dv">
 <script src="common.js"></script>
 <script>
  //點擊按鈕移動div
 
  my$("btn1").onclick = function () {
   animate(my$("dv"), 400);
  };
  my$("btn2").onclick = function () {
   animate(my$("dv"), 800);
  };
 
  //變速動畫
  function animate(element, target) {
   //清理定時器
   clearInterval(element.timeId);
   element.timeId = setInterval(function () {
    //獲取元素的當(dāng)前位置
    var current = element.offsetLeft;
    //移動的步數(shù)
    var step = (target-current)/10;
    step = step>0?Math.ceil(step):Math.floor(step);
    current += step;
    element.style.left = current + "px";
    if(current==target) {
     //清理定時器
     clearInterval(element.timeId);
    }
    
   }, 20);
  }
 </script>
</div>
</body>
</html>

common.js

/**
 * 獲取指定標(biāo)簽對象
 * @param id 標(biāo)簽的id屬性值
 * @returns {Element}根據(jù)id屬性值返回指定標(biāo)簽對象
 */
function my$(id) {
  return document.getElementById(id);
}

以上所述是小編給大家介紹的JS div勻速移動動畫與變速移動動畫詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評論