The implementation of a div can be dragged, the code is as follows:
<! DOCTYPE html>"en">"UTF-8"> <title>zzw_drap</title> <style> *{margin:0; padding:0; } #box {Position:absolute; top:100px; left:200px; width:500px; } #bar {padding-left:50px; height:50px; Line-height:50px; Color:white; Background-color: #aaa; Cursor:move; } #content {padding:30px0 050px; height:300px; Background-color: #eee; } </style>"Box"> <div id="Bar"> can drag the head </div> <div id="content"> here is content </div> </div> <script>/** Zzw.drag 2017-3 * JS Implementation div can be dragged * @params Bar can click on the dragged element * @params Box Drag the overall element must be position:absolute; * Thought: The Clienx/clienty relative value of the mouse is set to the relative value of the left/top of the parent element*/ varDragbox =function (drag, wrap) {function getcss (ele, prop) {returnparseint (window.getComputedStyle (ele) [prop]); } varInitx, inity, dragable=false, Wrapleft= Getcss (Wrap," Left"), Wrapright= Getcss (Wrap,"Top"); Drag.addeventlistener ("MouseDown", Function (e) {dragable=true; INITX=E.clientx; Inity=E.clienty; }, false); Drag.addeventlistener ("MouseMove", Function (e) {if(Dragable = = =true ) { varNOWX =E.clientx, Nowy=E.clienty, Disx= Nowx-Initx, Disy= Nowy-inity; Wrap.style.left= Wrapleft + Disx +"px"; Wrap.style.top= wrapright + Disy +"px"; } }); Drag.addeventlistener ("MouseUp", Function (e) {dragable=false; Wrapleft= Getcss (Wrap," Left"); Wrapright= Getcss (Wrap,"Top"); }, false); }; Dragbox (Document.queryselector ("#bar"), Document.queryselector ("#box")); </script></body>Where we can directly use the encapsulated function, which accepts two parameters, the first one can click on the dragged element, the second is the parent element. Note: The parent element's postion is set to absolute to be used.
JS to implement a draggable div