This plugin is written by the author of this blog, the purpose is to improve the author's JS ability, but also to some JS rookie in the use of plug-ins to provide some convenience, the birds fly leisurely.
This plugin is designed to achieve the most popular drag-and-drop effect, and you can set whether the dragged element can be dragged outside the viewable area according to your actual needs. The overall code is as follows:
<!DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /><title>Untitled Document</title><style>*{margin:0;padding:0;}. Box{position:Absolute; Left:100px;Top:100px;Border:1px solid #eee;width:150px;Height:150px;padding:10px;cursor:Move;}</style><Scripttype= "Text/javascript"src=".. /test/jquery-1.7.1.js "></Script><Scripttype= "Text/javascript"src= "Jquery.drag.js"></Script></Head><Body><Divclass= "box">Drag me!</Div><Script>$(function(){ $(". Box"). Drag ({out:false //false The default matching element cannot be dragged beyond the viewable area }); })</Script></Body></HTML>
Drag-and-drop plugin Jquery.drag.js code:
/**drag 0.1*copyright (c) 2015 small bad Http://tnnyang.cnblogs.com*dependenc jquery-1.7.1.js*/;(function(a) {A.fn.drag=function(options) {varDefaults = {//Default ParametersOutfalse //default matching elements are not dragged outside the viewable area } varopts =a.extend (defaults, options); This. each (function(){ varobj = A ( This); Obj.mousedown (function(e) {varE = e | | Event//differentiate between IE and other browser event objects varx = E.pagex-obj.offset (). Left;//gets the distance to the left of the matching element from the mouse vary = E.pagey-obj.offset (). Top;//gets the distance of the mouse from the top of the matching element$ (document). MouseMove (function(e) {varE = e | |event; var_x = E.pagex-x;//dynamically get element left distance var_y = E.pagey-y; if(!opts.out) { varMAXW = $ (window). Width ()-obj.outerwidth ();//The left edge of the visible area matches the left width of the element varMaxh = $ (window). Height ()-obj.outerheight ();//the height of the top of the visible area at the top of the matching element_x = _x < 0? 0: _x;//ensure that matching elements are not dragged outside the viewable area_x = _x > Maxw?Maxw: _x; _y= _y <0? 0: _y; _y= _y > Maxh?maxh: _y; }Else{_x=_x; _y=_y; } obj.css ({left:_x,top:_y}); }). MouseUp (function(){ $( This). Unbind ("MouseMove");//when the mouse lifts the delete move event match element stops moving }); }); })}) (jQuery);
Click to download drag and drop demo
jquery Plugin drag and drop