JS to implement a draggable div

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.