<! DOCTYPE html> <Html> <Head> <Meta charset = "UTF-8"/> <Title> perfect drag </title> <Style> Div { Width: 150px; Height: 150px; Background-color: #666; Position: absolute; Left: 50%; Top: 50%; Margin-left:-75px; Margin-top:-75px; Cursor: move; } </Style> </Head> <Body> <Div> </div> <Script src = "http://code.jquery.com/jquery-1.9.1.min.js"> </script> <Script> $ (Function (){ $ ("Div"). drag (); }); /* * Perfect drag */ $. Fn. drag = function (p ){ Var d = { // Parent element Parent: $ (document ), // Child element Child: $ (this ), // Whether the parent element is allowed to be exceeded IsBeyond: false }, O = $. extend (d, p || {}), IsMove = false, D = $ (this ), DW = $ (window). outerWidth ()-d. outerWidth (), DH = $ (window). outerHeight ()-d. outerHeight (), X = Y = XMove = YMove = 0 ; // Press the mouse to activate drag O. child. mousedown (function (e ){ IsMove = true; X = e. clientX-d. offset (). left; Y = e. clientY-d. offset (). top; D.css ({ "Position": "absolute ", "Z-index": "10" }); }); // Activate drag O. parent. mousemove (function (e ){ If (! IsMove) return; XMove = e. clientX-X; YMove = e. clientY-Y; If (! O. isBeyond ){ XMove = XMove> = 0? XMove: 0; XMove = DW> = XMove? XMove: DW; YMove = YMove> = 0? YMove: 0; YMove = DH> = YMove? YMove: DH; } D.css ({ "Left": XMove, "Top": YMove, "Margin-top": 0, "Margin-left": 0 }); Return false; }); // Release the mouse and drag it to the end. O. child. mouseup (function (e ){ IsMove = false; }); } </Script> </Body> </Html> |