2013-03-20 55 views
0

我試圖給div添加拖動柄,但div不移動,只是漢德爾。Div在移動時不跟隨拖動條

但是,如果我將位置改爲絕對位置以便應該移動的div,我實際上可以在div上移動,但是可以從任何地方移動,而不僅僅是拖動手柄。

任何提示?我爲此創建了一個jsfiddle。

http://jsfiddle.net/dymond/tQdFZ/11/

一些代碼。

var draggable = document.getElementsByClassName('hand'), 
     draggableCount = draggable.length, 
     i, currZ = 1; 
    function startDrag(evt) { 

     var diffX = evt.clientX - this.offsetLeft, 
      diffY = evt.clientY - this.offsetTop, 
      that = this; 
     this.style.opacity = "0.5"; 
     this.style.zIndex = currZ++; 

     function moveAlong(evt) { 
      that.style.left = (evt.clientX - diffX) + 'px'; 
      that.style.top = (evt.clientY - diffY) + 'px'; 
     } 
     function stopDrag() { 
      document.removeEventListener('mousemove', moveAlong); 
      document.removeEventListener('mouseup', stopDrag); 
      changeClass() 
     } 
     function changeClass() { 
      var diceClass = document.getElementsByClassName("hand"); 
      for (var i = 0; i < diceClass.length; i++) { 
       diceClass[i].style.opacity = "1"; 
      } 
     } 

     document.addEventListener('mouseup', stopDrag); 
     document.addEventListener('mousemove', moveAlong); 
    } 

    for (i = 0; i < draggableCount; i += 1) { 
     draggable[i].addEventListener('mousedown', startDrag); 
    } 

回答

1

嘗試設置CSS:

.draggable { position: absolute; ... 

,改變JS:

function moveAlong(evt) { 
    that.parentNode.style.left = (evt.clientX - diffX) + 'px'; 
    that.parentNode.style.top = (evt.clientY - diffY) + 'px'; 
} 

既然你要移動的parentNode,通過draging手柄..

+0

感謝。我認爲這是你第二次幫助我:) – Dymond 2013-03-21 01:17:11