拖放 Drag and drop 方法

虽然网上又很多实现方法,但是还是需要理解拖放原理。通过绑定onmousedown,onmousemove.onmouseup事件来实现层拖放位置变化,这只是很简单实现,可以去换个方法去实现。

<!DOCTYPE html>
<html>
<head>
<title>demo</title>
<style>
.drag1 , .drag2{
position:relative;
width:200px;
height:200px;
line-height: 200px;
text-align: center;
vertical-align: middle;
border-radius: 5px;
border:1px solid red;
}
</style>
</head>
<body>
<div id="drag1" class="drag1">
drag layer
</div>
</body>
<script>
// drag and drap class
function DND(el){
_startX = 0; // mouse starting positions
_startY = 0;
_offsetX = 0; // current element offset
_offsetY = 0;
_dragElement = el; // needs to be passed from OnMouseDown to OnMouseMove
_oldZIndex = 0; // we temporarily increase the z-index during drag
}

DND.prototype = {
init : function(){
var _this = this;
//replace with adeventListeners or attachEvent
document.onmousedown = function(e){_this.onMouseDown(e)};
document.onmouseup = function(e){_this.onMouseUp(e)};
},
onMouseDown: function(e){
var even = e ? e : window.event;
var target = e.target ? e.target : e.srcElement;
if(e.button == 1 || e.button == 0){
_startX = even.clientX;
_startY = even.clientY;
_offsetX = this.parseMumber(target.style.left);
_offsetY = this.parseMumber(target.style.top);
_oldZindex = target.style.zIndex;
_dragElement = target;

//replace with adeventListeners or attachEvent
document.onmousemove = this.onMouseMove;
// cancel out any text selections
document.body.focus();
// prevent text selection in IE
document.onselectstart = function () { return false; };
// prevent IE from trying to drag an image
target.ondragstart = function() { return false; };
return false;
}
},
onMouseMove: function(e){
var e = e ? e : window.event;
_dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px';
_dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px';
_dragElement.style.cursor ="move";

},
onMouseUp: function(e){
if(_dragElement){
//replace with adeventListeners or attachEvent
document.onmousemove = null;
document.onselectstart = null;
_dragElement.ondragstart = null;
_dragElement.style.cursor ="";
_dragElement = null;
}
},
parseMumber: function(value){
var n = parseInt(value);
return isNaN(n) ? 0 : n;
}
};

var dd1 = new DND(document.getElementById("drag1")).init();

</script>
</html>


参考:
[url]http://www.cnblogs.com/Godblessyou/archive/2008/05/14/1196746.html[/url]
[url]http://www.webreference.com/programming/javascript/mk/column2/[/url]
[url]http://luke.breuer.com/tutorial/javascript-drag-and-drop-tutorial.aspx[/url]
[url]http://www.quirksmode.org/js/dragdrop.html[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值