1

我有 div 的行为有点奇怪,当我第一次移动它时它工作得很好,但是第二次位置开始出现错误我有 position: absolute 在主 div 中,但仅此而已。

知道如何清除窃听器吗? http://jsfiddle.net/dymond/tQdFZ/14/ <-- jsfiddle

javascript。

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.parentNode.style.left = (evt.clientX - diffX) + 'px';
    that.parentNode.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);
    }

CSS

**.draggable {
 position: absolute; 
    width: 100px;
    height: 100px;
    background: red;
}

.hand{   
 cursor             : move;
 width: 98px;
min-height: 16px;
background: yellow;
border:1px solid black;

}
textarea{
   padding-top:20px;
    resize              : none;
    overflow            : hidden;
    background          : transparent;
    width:95px;
    border:none;
}
4

1 回答 1

2

offsetLeftand offsetTopofthis始终为 0,因为this指的是.hand不是.dragabble这样的:

    var diffX = evt.clientX - this.offsetLeft,
        diffY = evt.clientY - this.offsetTop,

应该是这样的:

    var diffX = evt.clientX - this.parentNode.offsetLeft,
        diffY = evt.clientY - this.parentNode.offsetTop,

更新小提琴:http: //jsfiddle.net/knoxzin1/tQdFZ/15/

于 2013-03-21T11:55:10.947 回答