开发者

Show an element relative to another with jQuery

I am working on an interface that requires that the user can click on a button, and then I will show a floating div positioned re开发者_StackOverflow社区lative to the button (you can kind of think of it as the area that shows when you click the down arrow on a dropdown).

How can I correctly position this floating element adjacent to the button which was clicked (which could be anywhere on the page)?

Thanks in advance!!


You can get the position of the button by using .offset()

For example:

$("#myButton").click(function() {
  var o = $(this).offset();
  $("#myDiv").css({'position': 'absolute','left':o.left,'top',o.top});
});

This would position it right on top of the button, just adjust that left/top wherever in relation you want it to go.

For example to place it below the button change the top portion to 'top': o.top + $(this).height() or to right right of the button: 'left':o.left + $(this).width()


<input type="button" id="btn" value="Choose Something" />

<div id="select">
  ...
</div>

with CSS:

#select { position: absolute; display: none; }

and Javascript:

$("#btn").click(function() {
  var sel = $("#select");
  var pos = $("#btn").offset();
  if (sel.is(":hidden")) {
    sel.attr({
      top: pos.top + 20,
      left: pos.left
    });
    sel.show();
  } else {
    sel.hide();
  }
});

Basically you absolutely position the floating div to remove it from the normal flow and then use offset() to figure out where to put it in relation to the button.


You should both get and set the position using .offset(), in case the element is positioned hierarchically.

For example2

<input type="button" id="myButton" value="Choose Something" 
     style="position: absolute; top: 100px;" />
<div style="position: absolute; top: 200px;">parent div
    <div id="myDiv" style="position: absolute; top: 20px;">child div</div>
</div>

$("#myButton").click(function () {
    var o = $(this).offset();
    $("#myDiv").offset({
        'left': o.left,
        'top': o.top - 20
    });
});

Here is a fiddle: http://jsfiddle.net/R5YM6/1/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜