<分区>
我有一个容器内的图像。我的要求是在容器内移动图像并获取其坐标。以前我使用可拖动功能来实现这一点。
但现在我希望通过使用箭头键 实现相同的行为。请帮忙。谢谢。
我之前的代码
HTML
<div id="claw" name='claw' style="overflow:hidden;width:320px;height:240px;position: relative; left: 0; top: 0;">
<img id='machine_image' />
<img id='pointer' src='images/circle.png' name='image' style="position: absolute; top: 105px; left: 145px;">
</div>
JQuery
$('#pointer').draggable({
cursor: 'move',
containment: '#claw',
stop: function () {
var cont = $('#claw').offset();
var img = $(this).offset();
x = img.left - cont.left;
y = img.top - cont.top;
}
});
最佳答案
这不是拖动 - 您需要监听 keydown
事件并自行处理移动图像。这对于 jQuery 来说并不难。
您基本上需要查看他们是否按下了箭头键,检查移动不会超出容器(如果这是您想要的),然后移动图像并存储新坐标。请注意,如果他们按住该键,它将重复调用 keydown
事件并且图像将继续移动。
// store x and y globally so you can use them wherever you need to
var x, y;
$(function() {
// set how many pixels to move on each press
var step = 5;
// cache references to pointer and claw jquery objects
var thePointer = $('#pointer');
var theClaw = $('#claw');
$('body').on('keydown', function(e) {
// get the current position
// this is already relative to claw so no need to work it out
var pos = thePointer.position();
// now check which key was pressed
switch(e.which)
{
case 38: // up
if(pos.top >= step) { // check it will not go out the container
pos.top -= step; // update the stored position
thePointer.css('top', pos.top + 'px'); // move the image
}
break;
case 40: // down
if(pos.top <= theClaw.height() - thePointer.height() - step) {
pos.top += step;
thePointer.css('top', pos.top + 'px');
}
break;
case 37: // left
if(pos.left >= step) {
pos.left -= step;
thePointer.css('left', pos.left + 'px');
}
break;
case 39: // right
if(pos.left <= theClaw.width() - thePointer.width() - step) {
pos.left += step;
thePointer.css('left', pos.left + 'px');
}
break;
// let other events through such as typing in textboxes.
default:
return;
}
// store the co-ordinates
x = pos.left;
y = pos.top;
console.log(x, y);
// prevent default event, usually page scrolling
return false;
});
$('body').on('keyup', function(e) {
// now check which key was pressed
switch(e.which)
{
case 37: case 38: case 39: case 40:
alert("Stopped at " + x + ", " + y);
break;
}
});
})
#claw {
background-color:yellow;
border:1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="claw" name='claw' style="overflow:hidden;width:320px;height:240px;position: relative; left: 0; top: 0;">
<img id='machine_image' />
<img id='pointer' src='http://maps.co.gov/aspnet_client/ESRI/WebADF/MarkerSymbols/circle-black-16x16.png' name='image' style="position: absolute; top: 105px; left: 145px;" />
</div>
<input type="text" placeholder="You can still type in me" />
关于javascript - 通过单击方向按钮在容器内移动图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27705910/