业务代码写多了或者养成了遇事百度的习惯之后,突然发现突然让自己一些最基本的动效都写不出来了,以后每天午休的时候就更新一个用原生js实现的动效,督促自己改掉这些坏毛病
- 元素拖拽效果
实现元素拖拽的要素就是鼠标事件监听,定位,还有对边界条件的控制,掌握这三点什么样的拖拽需求都可以了
实现方式:
<!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>