我想知道如何更改图像所在位置的X和Y坐标。因此,如果有人按下任何箭头键,图像将相应移动。 (以及根据鼠标位置旋转的图像)
$(function () {
var img = $('.image');
var offset = img.offset();
var value = 200;
function mouse(e) {
var centerX = (offset.left) + (img.width() / 2);
var centerY = (offset.top) + (img.height() / 2);
var mouse_x = e.pageX; var mouse_y = e.pageY;
var radians = Math.atan2(mouse_x - centerX, mouse_y - centerY);
var degree = (radians * (180 / Math.PI) * -1) + 90;
img.css('-webkit-transform', 'rotate(' + degree + 'deg)');
}
$(document).mousemove(mouse);
});
答案 0 :(得分:1)
您可以使用keydown事件执行此操作。您需要找到已按下的键(即上/左/右/下),并相应地绝对定位图像,如下所示:
$(document).keydown(function() {
var img = $('#img');
function moveLeft(value) {
img.css('left', function() {
return parseInt(img.css('left'), 10) + value + 'px';
});
}
function moveTop(value) {
img.css('top', function() {
return parseInt(img.css('top'), 10) + value + 'px';
});
}
switch(event.keyCode) {
// Left arrow
case 37:
moveLeft(-100);
break;
// Up arrow
case 38:
moveTop(-100);
break;
// Right arrow
case 39:
moveLeft(100);
break;
// Down arrow
case 40:
moveTop(100);
break;
}
});
当然,有一个优化的很多可以在这里完成,但它可以工作。
CodePen链接:http://codepen.io/anon/pen/qEbbMm