jQuery 如何使用jQuery将一个元素相对于另一个元素定位?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/158070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:43:29  来源:igfitidea点击:

How to position one element relative to another with jQuery?

jquery

提问by paul

I have a hidden DIV which contains a toolbar-like menu.

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

I have a number of DIVs which are enabled to show the menu DIV when the mouse hovers over them.

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

Is there a built-in function which will move the menu DIV to the top right of the active (mouse hover) DIV? I'm looking for something like $(menu).position("topright", targetEl);

是否有内置功能可以将菜单 DIV 移动到活动(鼠标悬停)DIV 的右上角?我正在寻找类似的东西$(menu).position("topright", targetEl);

采纳答案by Uriel

NOTE:This requires jQuery UI (not just jQuery).

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

You can now use:

您现在可以使用:

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

For fast positioning (jQuery UI/Position).

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

You can download jQuery UI here.

您可以在此处下载 jQuery UI

回答by Jacob

tl;dr:(try it here)

tl;博士:(在这里试试)

If you have the following HTML:

如果您有以下 HTML:

<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>

then you can use the following JavaScript code:

那么您可以使用以下 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();
});

But it doesn't work!

但它不起作用!

This will work as long as the menu and the placeholder have the same offset parent. If they don't, and you don't have nested CSS rules that care where in the DOM the #menuelement is, use:

只要菜单和占位符具有相同的偏移父级,这就会起作用。如果没有,并且您没有嵌套的 CSS 规则来关心#menu元素在 DOM 中的位置,请使用:

$(this).append($("#menu"));

just before the line that positions the #menuelement.

就在定位#menu元素的行之前。

But it still doesn't work!

但它仍然不起作用!

You might have some weird layout that doesn't work with this approach. In that case, just use jQuery.ui's position plugin(as mentioned in an answerbelow), which handles every conceivable eventuality. Note that you'll have to show()the menu element before calling position({...}); the plugin can't position hidden elements.

您可能有一些不适用于这种方法的奇怪布局。在这种情况下,只需使用jQuery.ui 的位置插件(如下面的答案中所述),它可以处理所有可能发生的情况。请注意,您必须show()在调用之前使用菜单元素position({...});该插件无法定位隐藏元素。

Update notes 3 years later in 2012:

3 年后的 2012 年更新说明:

(The original solution is archived herefor posterity)

(原始解决方案存档在这里供后代使用)

So, it turns out that the original method I had here was far from ideal. In particular, it would fail if:

所以,事实证明我在这里的原始方法远非理想。特别是,如果出现以下情况,它将失败:

  • the menu's offset parent is not the placeholder's offset parent
  • the placeholder has a border/padding
  • 菜单的偏移父级不是占位符的偏移父级
  • 占位符有边框/填充

Luckily, jQuery introduced methods (position()and outerWidth()) way back in 1.2.6 that make finding the right values in the latter case here a lot easier. For the former case, appending the menu element to the placeholder works (but will break CSS rules based on nesting).

幸运的是,jQuery在 1.2.6 中引入了方法(position()outerWidth()),这使得在后一种情况下更容易找到正确的值。对于前一种情况,append将菜单元素添加到占位符有效(但会破坏基于嵌套的 CSS 规则)。

回答by paul

This is what worked for me in the end.

这最终对我有用。

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

回答by Venkat D.

Here is a jQuery function I wrote that helps me position elements.

这是我编写的一个 jQuery 函数,可以帮助我定位元素。

Here is an example usage:

这是一个示例用法:

$(document).ready(function() {
  $('#el1').position('#el2', {
    anchor: ['br', 'tr'],
    offset: [-5, 5]
  });
});

The code above aligns the bottom-right of #el1 with the top-right of #el2. ['cc', 'cc'] would center #el1 in #el2. Make sure that #el1 has the css of position: absolute and z-index: 10000 (or some really large number) to keep it on top.

上面的代码将#el1 的右下角与#el2 的右上角对齐。['cc', 'cc'] 会将 #el1 放在 #el2 中。确保 #el1 具有 position: absolute 和 z-index: 10000 (或一些非常大的数字)的 css 以使其保持在顶部。

The offset option allows you to nudge the coordinates by a specified number of pixels.

偏移选项允许您将坐标微调指定数量的像素。

The source code is below:

源代码如下:

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

}

回答by gtamil

Why complicating too much? Solution is very simple

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

css:

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

It works even if,

即使它有效,

  • Two divs placed anywhere else
  • Browser Re-sized
  • 放置在其他任何地方的两个 div
  • 浏览器调整大小

回答by TLindig

You can use the jQuery plugin PositionCalculator

您可以使用 jQuery 插件PositionCalculator

That plugin has also included collision handling (flip), so the toolbar-like menu can be placed at a visible position.

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

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

for that markup:

对于该标记:

<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>

Here is the fiddle: http://jsfiddle.net/QrrpB/1657/

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

回答by devXen

This works for me:

这对我有用:

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

回答by slf

Something like this?

像这样的东西?

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