简体   繁体   English

浮动div坚持父母?

[英]floating div stick to parent?

i have a link which is placed ontop of a site. 我有一个链接放在网站的顶部。 when it is clicked , a DIV will be shown. 单击它时,将显示DIV。 the div will sit just below the LINK. div将位于LINK 正下方 if the link position from left is 215px , the DIV position from left will also be 215px. 如果左边的链接位置是215px,左边的DIV位置也是215px。 How can i track the position of the link to determine the position of the DIV so it could stick to it. 如何跟踪链接的位置以确定DIV的位置,以便它可以坚持下去。

<a href="link" id="link">Link</a>
<div id="float" style="display:none;">Some text</div>

jQuery: jQuery的:

$('#link').click(function(){
    $('#float').css('display','block');
});

Thanks. 谢谢。

The best way to stick something absolute positioned to something on the page is to wrap it with relative positioned element. 将绝对定位的东西粘贴到页面上的某些东西的最好方法是用相对定位的元素包装它。

You can try this: 你可以试试这个:

<div style="position: relative">
    <a href="link" id="link">Link</a>
    <div id="float" style="display:none; position: absolute; top: 10px; left: 0;">Some text</div>
</div>

Then you can position your floating element as you wish relative to the corners of the wrapping div (or other wrapping element) using left, top, right or bottom. 然后,您可以使用左,上,右或底部相对于包装div(或其他包装元素)的角定位浮动元素。

Serious advantage of that approach is that floating div will always be tied to the parent even if the window size is changed. 这种方法的明显优势在于,即使窗口大小发生变化,浮动div也总是与父级绑定。

JQuery has built in functions for getting positions of elements. JQuery内置了用于获取元素位置的函数。

See Offset for position related to document, or Position for position related to element's parent 请参阅与文档相关的位置的偏移量 ,或与元素的父级相关的位置的位置

Example to get the position of the link element... 获取链接元素位置的示例...

    $('#link').click(function () {
        var link = $(this);
        var linkOffset = link.offset();
        var xPos = linkOffset.left;
        var yPos = linkOffset.top;
        $('#float').css('display', 'block');
    });
<style>
#float {
  display:none;
  position:absolute;
  border:1px solid red;
  padding:5px;
  margin:0;
}
</style>

<a href="#" id="link">Link</a>
<div id="float">Some text</div>
<script>
$(function() {
  $("#link").click(function() {
    $("#float")
      .css("left", $(this).offset().left)
      .css("top", $(this).offset().top + $(this).height())
      .show();
  });
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM