我有一个隐藏的DIV,其中包含一个类似工具栏的菜单。

我有许多DIV,当鼠标悬停在它们上面时,它们可以显示菜单DIV。

是否有一个内置函数,将菜单DIV移动到活动(鼠标悬停)DIV的右上方?我在找像$(menu)这样的东西。位置(“topright targetEl);


当前回答

像这样的东西?

$(menu).css("top", targetE1.y + "px"); 
$(menu).css("left", targetE1.x - widthOfMenu + "px");

其他回答

你可以使用jQuery插件PositionCalculator

该插件还包括碰撞处理(翻转),因此类似工具栏的菜单可以放置在可见的位置。

$(".placeholder").on('mouseover', function() {
    var $menu = $("#menu").show();// result for hidden element would be incorrect
    var pos = $.PositionCalculator( {
        target: this,
        targetAt: "top right",
        item: $menu,
        itemAt: "top left",
        flip: "both"
    }).calculate();

    $menu.css({
        top: parseInt($menu.css('top')) + pos.moveBy.y + "px",
        left: parseInt($menu.css('left')) + pos.moveBy.x + "px"
    });
});

对于该标记:

<ul class="popup" id="menu">
    <li>Menu item</li>
    <li>Menu item</li>
    <li>Menu item</li>
</ul>

<div class="placeholder">placeholder 1</div>
<div class="placeholder">placeholder 2</div>

这是小提琴:http://jsfiddle.net/QrrpB/1657/

这对我来说很管用:

var posPersonTooltip = function(event) {
var tPosX = event.pageX - 5;
var tPosY = event.pageY + 10;
$('#personTooltipContainer').css({top: tPosY, left: tPosX});

注意:这需要jQuery UI(不仅仅是jQuery)。

你现在可以使用:

$("#my_div").position({
    my:        "left top",
    at:        "left bottom",
    of:        this, // or $("#otherdiv")
    collision: "fit"
});

用于快速定位(jQuery UI/Position)。

你可以在这里下载jQuery UI。

为什么这么复杂?解决方法很简单

css:

.active-div{
position:relative;
}

.menu-div{
position:absolute;
top:0;
right:0;
display:none;
}

jquery:

$(function(){
    $(".active-div").hover(function(){
    $(".menu-div").prependTo(".active-div").show();
    },function(){$(".menu-div").hide();
})

即使,

其他任何地方都有两个div 浏览器调整大小

这就是最后对我有用的方法。

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();
};