相对于开始拖动位置HTML5,Ember跟踪鼠标

时间:2013-10-17 19:49:13

标签: javascript jquery css html5 ember.js

从这个fiddle开始我想输出可拖动对象的坐标,因为它被拖动,相对于它的起始位置,它总是{0,0}。我知道我可以记录开始和结束拖动事件,如:

DragNDrop.Draggable = Ember.Mixin.create({
    attributeBindings: 'draggable',
    draggable: 'true',
    dragStart: function(event) {
        var dataTransfer = event.originalEvent.dataTransfer;
        dataTransfer.setData('Text', this.get('elementId'));
        console.log('begin coordinates: (0, 0)');
    },
    dragEnd: function(event) {
        console.log('end coordinates');  
    }
});

所以我有两个问题:

1.如何获得鼠标坐标?

2.如何在调用dragEnd函数之前继续输出鼠标坐标?

编辑:

For 1.我现在可以使用以下方法获取鼠标坐标:

DragNDrop.Draggable = Ember.Mixin.create({
    attributeBindings: 'draggable',
    draggable: 'true',
    dragStart: function(event) {
        var dataTransfer = event.originalEvent.dataTransfer;
        dataTransfer.setData('Text', this.get('elementId'));
        console.log('begin coordinates: ', event.originalEvent.pageX, event.originalEvent.pageY);
    },
    dragEnd: function(event) {
        console.log('end coordinates: ', event.originalEvent.pageX, event.originalEvent.pageY);  
    }
});

但是我仍然不确定如何连续输出当前的鼠标坐标,而不是在拖动开始时和拖动结束时只输出一次。

2 个答案:

答案 0 :(得分:5)

试试这个

DragNDrop.Draggable = Ember.Mixin.create({
    attributeBindings: 'draggable',
    draggable: 'true',
    dragStart: function(event) {
        var dataTransfer = event.originalEvent.dataTransfer;
        dataTransfer.setData('Text', this.get('elementId'));
        console.log('begin coordinates: ', event.originalEvent.pageX, event.originalEvent.pageY);
        },
        // track the drag
        drag: function(event) {
            console.log('tracking coordinates: ', event.originalEvent.pageX,  event.originalEvent.pageY); 
        },
        dragEnd: function(event) {
            console.log('end coordinates: ', event.originalEvent.pageX, event.originalEvent.pageY);  
        }
});

答案 1 :(得分:0)

此代码显示拖动时鼠标的坐标

HTML

<div id= 'draggable'></div>
<input type = 'text' value = 'test' id='myInput'/>

JQUERY

$(document).ready(function(e){
    $('#draggable').draggable();
    $('#draggable').on('drag' , function(event){
        $('#myInput').val(event.pageX + ',' + event.pageY);
    })
})

CSS

#draggable
{
    background-color:#EEE;
    width:200px;
    height:200px;
}

JSFIDDLE LINK