1. 程式人生 > 實用技巧 >HTML + JS實現一些基礎動效

HTML + JS實現一些基礎動效

業務程式碼寫多了或者養成了遇事百度的習慣之後,突然發現突然讓自己一些最基本的動效都寫不出來了,以後每天午休的時候就更新一個用原生js實現的動效,督促自己改掉這些壞毛病

  1. 元素拖拽效果

    實現元素拖拽的要素就是滑鼠事件監聽,定位,還有對邊界條件的控制,掌握這三點什麼樣的拖拽需求都可以了

實現方式:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"
> <title>實現拖拽效果</title> <style> *{ margin: unset; padding: unset; } html,body{ width: 100%; height: 100%; } .root{ width: 800px; height: 600px; margin: 10px auto
; padding: 20px; box-sizing: border-box; border: 1px solid red; border-radius: 8px; position: relative; } #box{ width: 100px; height: 100px; background-color: yellow; cursor: pointer
; position: absolute; top: 0; left: 0; } </style> </head> <body> <div class="root"> <div id="box">拖拽的元素</div> </div> <script> let drage = false; let p = null; let box = document.getElementById('box'); console.log(box); // 監聽滑鼠按下事件, 記錄初始位置 box.addEventListener('mousedown', (e) => { drage = true; p = [e.clientX, e.clientY]; }, false); document.addEventListener('mousemove', (e) => { if(!drage) return null; const x = e.clientX; const y = e.clientY; let resX = x - p[0]; let resY = y - p[1]; let left = parseInt(box.style.left || 0) + resX; let top = parseInt(box.style.top || 0) + resY; // 設定邊界條件 if(left < 0 || top < 0 || left > 700 || top > 500) return; box.style.left = left + 'px'; box.style.top = top + 'px'; p = [x, y]; }, false); document.addEventListener('mouseup', (e) => { drage = false; }, false); </script> </body> </html>