问题描述
我有一个jQuery按钮,当我按下它时,我想在它下面显示一个简单的div。
I have a jQuery button and I would like a simple div to appear under it when I press it.
我将div位置设置为相对但是怎么做无论按钮在哪里,我都将我的div放在按钮下面?
I have the div position set to relative but how do I position my div right under the button, no matter where the button is?
推荐答案
我会使用绝对定位,而不是相对。然后,在按钮的单击事件处理程序中,只需将div的顶部设置为等于按钮的顶部加上按钮的高度以及它们之间的所需空间。同样,将div的左侧设置为按钮的左侧。这些计算可以使用偏移量
和 outerHeight
生成div的方法,该div位于按钮下方并与按钮的左侧齐平。
I would use absolute positioning, instead of relative. Then, in the button's click event handler, just set the div's top equal the top of the button plus the height of the button plus what space you want between them. Similarly, set the div's left to the button's left. These calculations can use the offset
and outerHeight
methods to produce a div that is below the button and flush with the left side of the button.
例如。 ..
$('#btn').click(function() {
var btn = $(this);
$('#div').css({
position: 'absolute',
top: btn.offset().top + btn.outerHeight() + 10,
left: btn.offset().left
}).show();
});
如果你希望div相对于按钮居中或右对齐,那么调整相应地协调计算。
If you want the div to be centered or right-justified with respect to the button, then adjust the coordinate calculations accordingly.
这篇关于如何在按钮下方显示div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!