2014-12-05 74 views
-1

我想知道如何更改圖像所在的X和Y座標。因此,如果有人按下任何箭頭鍵,圖像將相應地移動。 (以及根據鼠標位置旋轉的圖像)更改圖像的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); 
}); 

回答

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