JQuery drag-and-drop plug-in implementation code_jquery
May 16, 2016 pm 06:07 PMMany page effects use these locations. As a last resort, you have to practice and remember.
Let’s talk about this simple drag-and-drop plug-in based on JQuery.
As usual, let’s first talk about the principle of drag and drop, and the steps to create such a thing:
So what is drag and drop? You can tell just by looking at the name: it drags something around. Putting it on our DOM means changing its position.
There are only two difficulties: 1. How to know if it is dragging? 2. How to know where to drag from and where to drag?
Actually, this is not difficult. After all, both are basic things. The key lies in proficiency.
Switch to js, we create a drag effect, the steps are as follows:
1. Let the element capture the event (usually, it is nothing more than mousedown, mousemove, mouseup)
2. During mousedown , marks the start of dragging, and obtains the position of the element and mouse.
3. During mousemove, continuously obtain the new position of the mouse, and reposition the element through the corresponding position algorithm.
4. During mouseup, end dragging. . . Then the cycle starts over again.
In the middle, there is one thing that needs attention: the dragged element needs to be at least relatively or absolutely positioned, otherwise the drag will have no effect.
OK, no more words, no code, no truth. The corresponding explanations are in it:
Download:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Jeremy - DragDrop Test !</title>
<meta name="keywords" content="Javascript自由拖拽类" />
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
(function($)
{
$.extend({
//获取鼠标当前坐标
mouseCoords:function(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY document.body.scrollTop - document.body.clientTop
};
},
//获取样式值
getStyle:function(obj,styleName)
{
return obj.currentStyle ? obj.currentStyle[styleName] : document.defaultView.getComputedStyle(obj,null)[styleName];
// return obj.currentStyle ? obj.currentStyle[styleName] : document.defaultView.getComputedStyle(obj,null).getPropertyValue(styleName);
}
});
// 元素拖拽插件
$.fn.dragDrop = function(options)
{
var opts = $.extend({},$.fn.dragDrop.defaults,options);
return this.each(function(){
//是否正在拖动
var bDraging = false;
//移动的元素
var moveEle = $(this);
//点击哪个元素,以触发移动。
//该元素需要是被移动元素的子元素(比如标题等)
var focuEle = opts.focuEle ? $(opts.focuEle,moveEle) : moveEle ;
if(!focuEle || focuEle.length<=0)
{
alert('focuEle is not found! the element must be a child of ' this.id);
return false;
}
// initDiffX|Y : 初始时,鼠标与被移动元素原点的距离
// moveX|Y : 移动时,被移动元素定位位置 (新鼠标位置与initDiffX|Y的差值)
// 如果定义了移动中的回调函数,该对象将以参数传入回调函数。
var dragParams = {initDiffX:'',initDiffY:'',moveX:'',moveY:''};
//被移动元素,需要设置定位样式,否则拖拽效果将无效。
moveEle.css({'position':'absolute','left':'0','top':'0'});
//点击时,记录鼠标位置
//DOM写法: getElementById('***').onmousedown= function(event);
focuEle.bind('mousedown',function(e){
//标记开始移动
bDraging = true;
//改变鼠标形状
moveEle.css({'cursor':'move'});
//捕获事件。(该用法,还有个好处,就是防止移动太快导致鼠标跑出被移动元素之外)
if(moveEle.get(0).setCapture)
{
moveEle.get(0).setCapture();
}
//(实际上是鼠标当前位置相对于被移动元素原点的距离)
// DOM写法:(ev.clientX document.body.scrollLeft - document.body.clientLeft) - document.getElementById('***').style.left;
dragParams.initDiffX = $.mouseCoords(e).x - moveEle.position().left;
dragParams.initDiffY = $.mouseCoords(e).y - moveEle.position().top;
});
//移动过程
focuEle.bind('mousemove',function(e){
if(bDraging)
{
//被移动元素的新位置,实际上鼠标当前位置与原位置之差
//实际上,被移动元素的新位置,也可以直接是鼠标位置,这也能体现拖拽,但是元素的位置就不会精确。
dragParams.moveX = $.mouseCoords(e).x - dragParams.initDiffX;
dragParams.moveY = $.mouseCoords(e).y - dragParams.initDiffY;
//是否限定在某个区域中移动.
//fixarea格式: [x轴最小值,x轴最大值,y轴最小值,y轴最大值]
if(opts.fixarea)
{
if(dragParams.moveX<opts.fixarea[0])
{
dragParams.moveX=opts.fixarea[0]
}
if(dragParams.moveX>opts.fixarea[1])
{
dragParams.moveX=opts.fixarea[1]
}
if(dragParams.moveY<opts.fixarea[2])
{
dragParams.moveY=opts.fixarea[2]
}
if(dragParams.moveY>opts.fixarea[3])
{
dragParams.moveY=opts.fixarea[3]
}
}
//移动方向:可以是不限定、垂直、水平。
if(opts.dragDirection=='all')
{
//DOM writing method: document.getElementById('***').style.left = '***px';
moveEle.css({'left':dragParams.moveX,'top':dragParams.moveY});
}
else if (opts.dragDirection=='vertical')
{
moveEle.css({'top':dragParams.moveY});
}
else if(opts.dragDirection=='horizontal')
{
moveEle.css({'left': dragParams.moveX});
}
//If there is a callback
if(opts.callback)
{
//Pass dragParams as parameters
opts.callback.call( opts.callback,dragParams);
}
}
});
//When the mouse bounces up, mark it as canceling the move
focuEle.bind('mouseup',function(e) {
bDraging=false;
moveEle.css({'cursor':'default'});
if(moveEle.get(0).releaseCapture)
{
moveEle.get (0).releaseCapture();
}
});
});
};
//Default configuration
$.fn.dragDrop.defaults =
{
focusEle:null, //Which element is clicked to start dragging, can be null. When not empty, it needs to be a child element of the dragged element.
callback:null, //Callback triggered when dragging.
dragDirection:'all', //Drag direction: ['all','vertical','horizontal']
fixarea:null //Limit the area to be dragged, provided in the form of an array [minX, maxX,minY,maxY]
};
})(jQuery);
// test
$(function(){
//Limited area, with callback function.
$('#dragDiv').dragDrop({fixarea:[0,$('#dragContainer').width()-50,0,$('#dragContainer').height()-50],callback:function (params){
$('#span1').text('X:' params.moveX ' Y:' params.moveY);
}});
//Default setting
$('#dragDiv1').dragDrop();
});
</script>
</head>
<body>
<div id=" dragContainer" style="position:relative;left:10px;top:10px;border:1px dashed blue;width:500px;height:500px;">
<div id="dragDiv" style="background- color:blue;height:50px;width:50px;">
</div>
<div id="dragDiv1" style="border:1px solid red;height:50px;width:50px ;">
</div>
</div>
<span id="span1"></span>
</body>
< ;/html>

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Detailed explanation of jQuery reference methods: Quick start guide

How to use PUT request method in jQuery?

How to remove the height attribute of an element with jQuery?

jQuery Tips: Quickly modify the text of all a tags on the page

Use jQuery to modify the text content of all a tags

In-depth analysis: jQuery's advantages and disadvantages

Understand the role and application scenarios of eq in jQuery

How to tell if a jQuery element has a specific attribute?
