单击以将div移动到鼠标坐标

Bar*_*der 0 html javascript css jquery

我有以下代码:http:
//www.project-vanquish.co.cc/gridtest/drag-grid.html

计划是允许用户以3种方式控制该div(带笑脸):
1 - 通过键盘上的光标键
2 - 通过拖动div
3 - 通过单击一个区域,div将移动到位置

我遇到的问题是,当我点击页面时,div似乎略微偏移到应该是什么:(

此外,"点击移动"方法在IE中根本不起作用.

我以为我昨晚搞过这个,显然不是......

gbl*_*zex 8

您需要调整它,mouse coordinates因为它们absolute(来自事件对象)但您可以relative在地图上进行调整.

所以你需要地图的坐标,并在每次点击发生时从鼠标点击坐标中减去它们.

您还必须标准化单击坐标以处理角色的中心(而不是左上角).所以,你需要减去一半的的字符的宽度和高度从鼠标坐标.

[ 看到它在行动 ]

var mapTop     = $('#map').offset().top;
var mapLeft    = $('#map').offset().left;
var charWidth  = $('#character').outerWidth();
var charHeight = $('#character').outerHeight();

$('#map').click(function (e) {
    var mouseX = e.pageX - mapLeft - (charWidth / 2);  // convert absolute coords
    var mouseY = e.pageY - mapTop  - (charHeight / 2); // into relative ones...
    mouseX = Math.round(mouseX / 40) * 40;
    mouseY = Math.round(mouseY / 40) * 40;
    $('#character').animate({
        top: mouseY,
        left: mouseX
    })
});
Run Code Online (Sandbox Code Playgroud)