简体   繁体   English

相对div内部的动态定位

[英]Dynamic positioning inside relative div

I'm trying to get a color picker javascript widget working in a page with a bunch of "stuff" in it that I can't change. 我正在尝试使颜色选择器javascript小部件在页面上工作,并且其中包含一堆我无法更改的“东西”。 Some of the "stuff" is causing the color picker to appear well below the link when clicked. 单击某些“材料”会使颜色选择器显示在链接下方。 I've reduced it to a simple example below. 我将其简化为下面的简单示例。

What's supposed to happen is when you click "link 1", "div1" should move directly below "link 1". 应该发生的是,当您单击“链接1”时,“ div1”应直接移到“链接1”下方。 What actually happens is that "div 1" appears well below "link 1". 实际上发生的是“ div 1”出现在“ link 1”下方。 If you remove position: relative; 如果删除position: relative; from the CSS definition for divMain , "div 1" is positioned correctly. divMain的CSS定义中,“ div 1”的位置正确。

How can I position "div 1" directly beneath "link 1" without removing position: relative; 如何在不删除position: relative;情况下将“ div 1”直接定位在“链接1”下方position: relative; ?

 function setPos(aname, dname) { var o = document.getElementById(aname); var ol = o.offsetLeft; while ((o = o.offsetParent) != null) { ol += o.offsetLeft; } o = document.getElementById(aname); var ot = o.offsetTop + 25; while ((o = o.offsetParent) != null) { ot += o.offsetTop; } document.getElementById(dname).style.left = ol + "px"; document.getElementById(dname).style.top = ot + "px"; } 
 h1 { height: 50px; } #divMain { position: relative; } 
 <h1></h1> <div id="divMain"> <a href="#" onClick="setPos('link1','div1');return false;" name="link1" id="link1">link 1</a> <div id="div1" style="position:absolute;border-style:solid;left:200px;top:200px;">div 1</div> </div> 

The position of the div is relative to the innermost container with its position set. div的位置相对于设置了其位置的最里面的容器。 So in this case, it's ending up 200px rightwards and downwards from divMain. 因此,在这种情况下,它从divMain向右下方向下移动200px。 Without position set on divMain, it's positioned relative to body. 在divMain上未设置位置的情况下,它相对于主体定位。

If you want it right below the link, put both the link1 and div1 inside an element with position. 如果要在链接正下方,请将link1和div1都放在具有位置的元素内。 So change it to this: 因此,将其更改为:

<div id="divMain">
    <div style="position:relative;">
        <a href="#" onClick="setPos('link1','div1');return false;" name="link1" id="link1">link 1</a>
        <div id="div1" style="position:absolute;border-style:solid;left:0px;top:16px;">div 1</div>
    </div>
</div>

(Note that I pop it down by 16px still, to put it below the link.) (请注意,我仍将其向下弹出16像素,以将其放置在链接下方。)

So this means now that div1 is 0px,16px from the div I added, rather than from divMain. 因此,这意味着现在div1从我添加的div(而不是divMain)开始为0px,16px。

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

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