How to make a div appear under button
I have a jQuery button and I would like a simple div to appear under it when I press it.
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?
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
[API] and outerHeight
[API] methods to produce a div that is below the button and flush with the left side of the button.
For example...
$('#btn').click(function() {
var btn = $(this);
$('#div').css({
position: 'absolute',
top: btn.offset().top + btn.outerHeight() + 10,
left: btn.offset().left
}).show();
});
If you want the div to be centered or right-justified with respect to the button, then adjust the coordinate calculations accordingly.
This answer might depend on your CSS, but to append a div
after the button in the DOM:
$('#button_id').click(
function(){
$('<div />').insertAfter($(this));
return false;
});
JS Fiddle demo.
References:
click()
.insertAfter()
;
精彩评论