div/dom元素拖拽縮放外掛,純js實現拖拽縮放,不依賴jQuery~
阿新 • • 發佈:2019-01-08
產品需求,需要用到對div(dom)進行拖拽縮放操作,看到有好多外掛,要麼依賴jQuery,要麼檔案太大。
封裝了一個外掛,不壓縮狀態下5KB。
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>demo</title> <style> * { margin: 0; padding: 0; } html, body { width: 100%; height: 100%; } .box { width: 200px; height: 200px; border: 1px dashed #ccc; position: absolute; left: 50px; top: 50px; } .content { width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; font-size: 28px; } .dragHandle { width: 15px; height: 15px; border-radius: 50%; background: #000; position: absolute; left: 0; top: -15px } .resizeHandle { display: block; position: absolute; width: 10px; height: 10px; border-right: 2px solid #b2b2b2; border-bottom: 2px solid #b2b2b2; right: 0px; bottom: 0px; overflow: hidden; cursor: nw-resize; } </style> </head> <body> <div class="box"> <div class="content"> Candy </div> <div class="dragHandle"> </div> <div class="resizeHandle"> </div> </div> </body> </html> <script src="./drag.js"> </script> <script> //父元素相對定位 relative //當前拖動元素絕對定位 absolute let elem = document.querySelector(".box") let dragHandle = document.querySelector(".dragHandle") let resizeHandle = document.querySelector(".resizeHandle") let drag = new Draggable(elem, dragHandle, resizeHandle, true, (dragStyle) => { console.log("當前元素現在的位置",dragStyle) }, (resizeStyle) => { console.log("當前元素現在的寬高",resizeStyle) }); </script>
js在github上,順便點個星吧,謝謝啦: