我在容器中有一个图片。我的要求是将图像移动到容器内并获得其坐标。以前我使用可拖动功能来实现这一目标。
但现在我想使用箭头键来保持相同的行为。请帮忙。感谢。
我之前的代码
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;
}
});
答案 0 :(得分:1)
这不是拖动 - 您需要收听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;
}
});
})
&#13;
#claw {
background-color:yellow;
border:1px solid #000;
}
&#13;
<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" />
&#13;