您的位置:首页 > Web前端 > JQuery

jQuery实现自由拖动DIV插件

2017-01-12 14:10 465 查看
实现简单Div的拖动效果,主要分为三步。

1,需要拖动的Div拖动绑定,mousedown事件,鼠标mousedown的时候记录此时的鼠标相对浏览器的x轴和y轴,以及需要拖动Div的相对浏览器的left,top值,并且给拖曳标记赋值为true,代表拖动动作就绪。

2,绑定鼠标的移动事件,因为光标在DIV元素外面也要有效果,所以要用实现拖动区域的Div上绑定事件,而不用DIV元素的事件 ,mousemove事件动态获取鼠标的x轴和y轴值,然后计算出拖动Div的新的left和top值,并重新赋值改变css使其实现拖动效果。

3,鼠标mouseup事件触发时,拖动标记赋值为false,结束拖动。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>拖动DIV</title>
<style type="text/css">
.wrapper{
width: 600px;
height :600px;
background-color: lightgreen;
}
.content{
width: 200px;
height: 200px;
background-color: #ccc;
position: absolute;

}

</style>

</head>
<body>
<div class="wrapper">
<div class="content">
拖动Div
</div>
</div>
<p>鼠标指针的坐标是: <span></span>.</p>
</body>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('.content').dragDiv();
})

;(function($) {
$.fn.dragDiv = function(options) {
return this.each(function() {
var _moveDiv = $(this);//需要拖动的Div
var _moveArea = options ? $(options) : $(document);//限定拖动区域,默认为整个文档内
var isDown = false;//mousedown标记
//ie的事件监听,拖拽div时禁止选中内容,firefox与chrome已在css中设置过-moz-user-select: none; -webkit-user-select: none;
if(document.attachEvent){
_moveDiv[0].attachEvent('onselectstart', function() {
return false;
});
}
_moveDiv.mousedown(function(event) {
var e = event || window.event;
//拖动时鼠标样式
_moveDiv.css("cursor", "move");
//获得鼠标指针离DIV元素左边界的距离
var x = e.pageX - _moveDiv.offset().left;
//获得鼠标指针离DIV元素上边界的距离
var y = e.pageY - _moveDiv.offset().top;
_moveArea.on('mousemove', function(event) {
var ev = event || window.event;
//获得X轴方向移动的值
var abs_x = ev.pageX - x;
//获得Y轴方向移动的值
var abs_y = ev.pageY - y;
//div动态位置赋值
_moveDiv.css({'left': abs_x, 'top': abs_y});
})
});
_moveDiv.mouseup(function() {
_moveDiv.css('cursor', 'default');
//解绑拖动事件
_moveArea.off('mousemove');

});

})
}
})(jQuery)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery