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>