问题描述
我正在尝试使用jQuery来检测div的位置( #olddiv
),所以我可以使用该位置放置另一个div( #newdiv
)正好在它下面。 2个div的右边框对齐(右边框)。
I'm trying to use jQuery to detect the position of a div (#olddiv
), so I can use that position to place another div (#newdiv
) exactly below it. The right borders of the 2 divs are aligned (right border).
我正在尝试将 #olddiv
底部和正确的位置用作 #newdiv
顶部和右侧边框。我已经使用了这个代码,但是它不起作用。任何想法我做错了什么?
I'm trying to get the #olddiv
bottom and right locations to use them as the #newdiv
top and right borders. I've used this code, but it's not working. Any idea what I'm doing wrong?
var right = $('#olddiv').position().right;
var top = $('#olddiv').position().bottom;
$('#newdiv').css('top', right);
$('#newdiv').css('right', top);
另外,我不知道如果位置
是我需要的我认为这可以用位置
或 offset
完成,但我不确定:
Also, I'm not sure if position
is what I need. I think this can be done with position
or offset
, but I'm not sure:
$('#ID').position().left
$('#ID').offset().left
谢谢
推荐答案
我已经使用offset()来动态定位元素。尝试这样:
I've used offset() to position elements dynamically. Try this:
var offset = $('#olddiv').offset();
var height = $('#olddiv').height();
var width = $('#olddiv').width();
var top = offset.top + height + "px";
var right = offset.left + width + "px";
$('#ID').css( {
'position': 'absolute',
'right': right,
'top': top
});
也不要忘记绑定到 window.onresize
事件,如果您需要它在用户调整窗口大小时缩放。
also don't forget to bind this to the window.onresize
event if you need it to scale when the user resizes the window.
更新:另一个想法 - 绝对定位?为什么不在DOM中插入另一个div?
UPDATE: another thought - does this have to be positioned absolutely? Why not just insert the div after the other in the DOM?
$('#olddiv').after($('#ID').html());
然后确定它们的宽度相同。
then just make sure they are the same width.
这篇关于如何将div定位在另一个之下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!