我有这个HTML:
<div class="info">
Some Text Boom A <a onclick="menu('id1');">Link</a> | More text
<a onclick="menu('id2');">Another Link</a> | more text
<ul id="id1" class="submenu">
<li><a href="dfhdfh">A1</a></li>
<li><a href="aetjetjsd">A2 This is Long</a></li>
<li><a href="etetueb">A3</a></li>
</ul>
<ul id="id2" class="submenu">
<li><a href="dfhdfh">B1</a></li>
<li><a href="aetjetjsd">B2</a></li>
<li><a href="etetueb">B3</a></li>
</ul>
</div>
JavaScript的:
function menu(id) {
var myLayer = document.getElementById(id);
if (myLayer.style.display == "none" || myLayer.style.display == "") {
myLayer.style.display = "block";
} else {
myLayer.style.display = "none";
}
}
CSS:
.info ul.submenu
{
border: solid 1px #000;
border-top: none;
background-color: #fff;
position: relative;
top: 4px;
width: 150px;
padding: 6px 0px 0px 0px;
z-index: 2;
display: none;
}
.info ul.submenu li
{
display: block;
border: none;
border-top: solid 1px #00ff00;
}
.info ul.submenu li a
{
display: block;
padding: 6px 0px 6px 4px;
color: #ff0000;
}
.info ul.submenu li a:hover
{
background: #0000ff;
}
当我点击第一个链接时,这就是我想要的样子:
---------------------------------------------------------------------
Text Boom A [Link] | More Text [Another Link] | more text
---------------------------------------------------------------------
Stuff that i| A1 |iv is still shown. Text that is
underneath t| A2 This is Long |own. Text that is underneath the div
is still sho| A3 |
现在这种作品,除了A1,A2,A3弹出窗口总是对齐到最左边的。如何修复我的CSS和/或HTML以实现此效果?
答案 0 :(得分:1)
您必须手动为left
元素设置ul
样式。
在javascript中:
function menu(eSrc, id) {
var myLayer = document.getElementById(id);
if (myLayer.style.display == "none" || myLayer.style.display == "") {
myLayer.style.display = "block";
myLayer.style.left = eSrc.offsetLeft + "px";
myLayer.style.top = (eSrc.offsetTop + eSrc.offsetHeight) + "px";
} else {
myLayer.style.display = "none";
}
}
然后,HTML将是:
<div class="info">
Some Text Boom A <a onclick="menu(this, 'id1');">Link</a> | More text
<a onclick="menu(this, 'id2');">Another Link</a> | more text
<ul id="id1" class="submenu">
<li><a href="dfhdfh">A1</a></li>
<li><a href="aetjetjsd">A2 This is Long</a></li>
<li><a href="etetueb">A3</a></li>
</ul>
<ul id="id2" class="submenu">
<li><a href="dfhdfh">B1</a></li>
<li><a href="aetjetjsd">B2</a></li>
<li><a href="etetueb">B3</a></li>
</ul>
</div>
您必须传递“reference”元素,以便知道元素的位置。
此外,要实现此目的,请在CSS中将position:relative;
更改为position:absolute;
。