[英]How can I find the coordinates of a movable div in Jquery
How can I find the coordinates of my movable div? 如何找到可移动div的坐标? I want to be able to find the coordinates after it has been moved so that I can add boundaries to the game, have it shoot lasers from the divs location etc. Thank you very much in advance!
我希望能够在移动后找到坐标,以便为游戏添加边界,让它从divs位置发射激光,等等。在此先非常感谢!
edit: 编辑:
I tried using this: 我尝试使用此:
var offsets = $('#img').offset();
var top = offsets.top;
var left = offsets.left;
if (left > 0) {$('#img').animate({left: "-=10px"}, 'fast');}
this didn't work so I test to see what was happening by putting: 这没有用,所以我通过输入以下内容来测试正在发生的情况:
setTimeout(function() {alert(left);}, 5000);
I then moved it around and discovered that it wasn't updating the location of the Div as after the alert activated it gave me a number that wasn't the original css value but was close to it which may be because it's an irregular div or just the way offset works. 然后我四处移动,发现它并没有更新Div的位置,因为警报激活后,它给了我一个不是原始css值但接近的数字,可能是因为它是不规则的div或只是偏移量起作用的方式。
var state = 1;
$(document).ready(function() {
$(document).keydown(function(key) {
if(state == 1) {
switch(parseInt(key.which,10)) {
// Left
case 37:
$('#img').animate({left: "-=10px"}, 'fast');
state = 2;
setTimeout(function() {
state = 1;
}, 200);
break;
// Up
case 38:
$('#img').animate({top: "-=10px"}, 'fast');
state = 2;
setTimeout(function() {
state = 1;
}, 200);
break;
// Right
case 39:
$('#img').animate({left: "+=10px"}, 'fast');
state = 2;
setTimeout(function() {
state = 1;
}, 200);
break;
// Down
case 40:
$('#img').animate({top: "+=10px"}, 'fast');
state = 2;
setTimeout(function() {
state = 1;
}, 200);
break;
}
}
});
});
Use jQuery.offset()
to get an offset coordinates relative to the document or jQuery.position()
to get coordinates relative to the offset of the parent element. 使用
jQuery.offset()
获取相对于文档的偏移坐标,或者使用jQuery.position()
获取相对于父元素的偏移的坐标。
Both methods will return you an object with properties top
and left
. 这两种方法都会返回一个具有
top
和left
属性的对象。
var $movableDiv = $('#img'),
imgAbsolutePosition,
setImgAbsolutePosition;
setImgAbsolutePosition = function() {
imgAbsoultePosition = $movableDiv.offset();
};
$('#img').animate({top: "+=10px"}, {
duration: 'fast',
complete: setImgAbsolutePosition
});
If the position of an element is changed you'll have to retrieve it again with jQuery.offset()
and update your variables left
and top
. 如果元素的位置更改,则必须使用
jQuery.offset()
再次检索它,并更新left
和top
变量。
it gave me a number that wasn't the original css value but was close to it
它给了我一个不是原始CSS值但与之接近的数字
Take into account border
, padding
and margin
of the element and its container. 考虑元素及其容器的
border
, padding
和margin
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.