Drag and Drop restrictions, magnetic adsorption ., Drag Range Magnetic Adsorption

Source: Internet
Author: User

Drag and Drop restrictions, magnetic adsorption ., Drag Range Magnetic Adsorption

<! DOCTYPE html>
<Html lang = "en">
<Head>
<Meta charset = "UTF-8">
<Title> Document </title>
<Style type = "text/css">
Body {
Margin: 0;
}
# Wrap {
Margin: 50px auto;
Position: relative;
Border: 1px solid #000;
Width: 600px;
Height: 500px;
}
# Div {
Position: absolute;
Left: 0;
Top: 0;
Width: 100px;
Height: 100px;
Background: red;
Cursor: move;
}
</Style>
</Head>
<Body>
<Div id = "wrap">
<Div id = "div"> text </div>
</Div>
<Script type = "text/javascript">
(Function (){
Var div = document. querySelector ('# div ');
Var maxX = div. offsetParent. clientWidth-div. offsetWidth;
Var maxY = div. offsetParent. clientHeight-div. offsetHeight;
Div. addEventListener ('mousedown ', function (e ){
E. preventDefault ();
Var start = {x: e. clientX, y: e. clientY };
Var elOffset = {x: div. offsetLeft, y: div. offsetTop };
Document. addEventListener ('mousemove ', move );
Document. addEventListener ('mouseup', end );
Function move (e ){
Var dis = {x: e. clientX-start. x, y: e. clientY-start. y };
Var x = dis. x + elOffset. x;
Var y = dis. y + elOffset. y;
/* Magnetic adsorption on the left */
X = x <0? 0 :( x> maxX? MaxX: x );

Y = y <0? 0 :( y> maxY? MaxY: y );
Console. log (x );
Div. style. left = x + "px ";
Div. style. top = y + "px ";
}
Function end (e ){
Document. removeEventListener ('mousemove ', move );
Document. removeEventListener ('mouseup', end );
Var dis = {x: e. clientX-start. x, y: e. clientY-start. y };
Var x = dis. x + elOffset. x;
Var y = dis. y + elOffset. y;
/* Magnetic adsorption on the left */
X = x <100? 0 :( x> maxX? MaxX: x );
/* Above magnetic adsorption */
Y = y <100? 0 :( y> maxY? MaxY: y );
Console. log (x );
Div. style. left = x + "px ";
Div. style. top = y + "px ";
}
});

})();
</Script>
</Body>
</Html>

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.