一、開篇
在上一篇中,似乎不出來這個架構有多強大。是因為我們實現的效果太簡單了,還不足以體現架構的強大和靈活,在這一節中,用這個靈活的架構輕易的來實現拖放!
二、原理
架構的原理在上一篇文章中介紹了,這裡就不在重複,直接開始使用這個架構了
首先通過Drag.init來註冊拖動組件;
分析:
1、拖動開始的時候
將dragGhost插入到滑鼠拖動的那個元素,滑鼠拖動的元素的position為absolute
dragGhost為拖動過程中指示拖動元素的當前位置的元素
2、拖動進行中的時候
根據當前滑鼠的位置或者正在被滑鼠拖動的元素的位置 和需要排列的各種元素來比較,以確定將dragGhost放在哪個地方。
具體的分析,就是遍曆拖動元素的各個兄弟元素,從第一元素起,一旦發現某個元素的x和y比滑鼠的x和y大的話,則將dragGhost添加到這個元素之前。
3、拖動結束的時候
將dragGhost替換為被拖動的元素,然後將dragGhost隱藏。
這樣就讓思路很清晰,不必再花精力去管元素是怎麼隨著滑鼠走的,而且我們的卻很精確的控制了整個拖放過程,所以說這個架構很強大很靈活
三、代碼
Code
function findPosX(obj) {//輔助函數 得到元素左邊與瀏覽器左邊的邊距
var curleft = 0;
if (obj && obj.offsetParent) {
while (obj.offsetParent) {
curleft += obj.offsetLeft;
obj = obj.offsetParent;
}
} else if (obj && obj.x) curleft += obj.x;
return curleft;// + document.body.scrollLeft - document.body.clientLeft;
}
function findPosY(obj) {//輔助函數 得到元素上邊與瀏覽器上邊的邊距
var curtop = 0;
if (obj && obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop;
obj = obj.offsetParent;
}
} else if (obj && obj.y) curtop += obj.y;
return curtop;// + document.body.scrollTop - document.body.clientTop;
}
var dragGhost;
var container;
window.onload = function(){
dragGhost = document.getElementById("dragGhost");
container = document.getElementById("container");
var nodes = container.getElementsByTagName("li");
for(var i=0;i<nodes.length;i++){
var li = nodes[i];
if(li.id != "dragGhost"){
new dragItem(li);
}
}
}
var isIE = document.all;
function dragItem(item){
Drag.init(item,item);
item.onDragStart = function(left,top,mouseX,mouseY){
this.style.left = findPosX(this);
this.style.top = findPosY(this);
this.style.position = "absolute";
//將ghost插入到當前位置
dragGhost.style.display = "block";
dragGhost.style.width = isIE?this.offsetWidth:this.offsetWidth - 2;//邊框問題
dragGhost.style.height = isIE?this.offsetHeight:this.offsetHeight - 2;
this.parentNode.insertBefore(dragGhost,this);
}
item.onDrag = function(left,top,mouseX,mouseY){
var nodes = container.getElementsByTagName("li");
var width = this.offsetWidth;
var height = this.offsetHeight;
for(var i=0;i<nodes.length + 1;i++){
if(nodes[i] == null){
container.appendChild(dragGhost);//拖動最後一項
break;
}
if(nodes[i].id == "dragGhost" || nodes[i] == this){
continue;
}
if(mouseX < findPosX(nodes[i]) + width
&& mouseY < findPosY(nodes[i]) + height){
container.insertBefore(dragGhost,nodes[i]);
break;
}
}
}
item.onDragEnd = function(left,top,mouseX,mouseY){
container.insertBefore(this,dragGhost);
this.style.position = "static";
this.style.display = "block";
dragGhost.style.display = "none";
}
}
四、樣本下載
點此下載樣本