<div id="menu" style="display: none;">
<!-- menu stuff in here -->
<ul><li>Menu item</li></ul>
</div>
<div class="parent">Hover over me to show the menu here</div>
然后你可以使用下面的JavaScript代码:
$(".parent").mouseover(function() {
// .position() uses position relative to the offset parent,
var pos = $(this).position();
// .outerWidth() takes into account border and padding.
var width = $(this).outerWidth();
//show the menu directly over the placeholder
$("#menu").css({
position: "absolute",
top: pos.top + "px",
left: (pos.left + width) + "px"
}).show();
});
var showMenu = function(el, menu) {
//get the position of the placeholder element
var pos = $(el).offset();
var eWidth = $(el).outerWidth();
var mWidth = $(menu).outerWidth();
var left = (pos.left + eWidth - mWidth) + "px";
var top = 3+pos.top + "px";
//show the menu directly over the placeholder
$(menu).css( {
position: 'absolute',
zIndex: 5000,
left: left,
top: top
} );
$(menu).hide().fadeIn();
};
jQuery.fn.getBox = function() {
return {
left: $(this).offset().left,
top: $(this).offset().top,
width: $(this).outerWidth(),
height: $(this).outerHeight()
};
}
jQuery.fn.position = function(target, options) {
var anchorOffsets = {t: 0, l: 0, c: 0.5, b: 1, r: 1};
var defaults = {
anchor: ['tl', 'tl'],
animate: false,
offset: [0, 0]
};
options = $.extend(defaults, options);
var targetBox = $(target).getBox();
var sourceBox = $(this).getBox();
//origin is at the top-left of the target element
var left = targetBox.left;
var top = targetBox.top;
//alignment with respect to source
top -= anchorOffsets[options.anchor[0].charAt(0)] * sourceBox.height;
left -= anchorOffsets[options.anchor[0].charAt(1)] * sourceBox.width;
//alignment with respect to target
top += anchorOffsets[options.anchor[1].charAt(0)] * targetBox.height;
left += anchorOffsets[options.anchor[1].charAt(1)] * targetBox.width;
//add offset to final coordinates
left += options.offset[0];
top += options.offset[1];
$(this).css({
left: left + 'px',
top: top + 'px'
});
}