停止下拉导航栏从推动元素旁边

时间:2014-12-08 14:04:57

标签: javascript html css navigationbar

我有一个下拉导航栏,当页面上的按钮或图像等元素太高时,当出现下拉选项时,导航栏会将元素推到右侧。我该如何阻止它?

导航栏:

<nav id="nav1">

<ul>

<li><a href="#" onmousedown="Sound.play()">Home</a></li>

<li onmouseover = "DropDown1()" onmouseout="DropUp1()"><a href="#" onmousedown="Sound.play()">Images</a><ul   class="DropUp" id="Droplist1" >
<li class="DropDown"><a id="Droplist1" href="#">Test1</a></li>
<li class="DropDown"><a href="#">Test2</a></li>
<li class="DropDown"><a href="#">Test3</a></li></ul>
</li>

<li onmouseover = "DropDown2()" onmouseout="DropUp2()"><a href="#" onmousedown="Sound.play()">Adverts</a><ul id="Droplist2"  class="DropUp">

<li class="DropDown"><a  href="#">Test1</a></li>
<li class="DropDown"><a  href="#">Test2</a></li></ul>
</li>


<li><a href="#" onmousedown="Sound.play()">Data Validation</a></li>

<li><a href="#" onmousedown="Sound.play()">Security</a></li>

</ul>
</nav>

CSS:

nav#nav1 li a {
    display: block;
    padding: 3px 8px;
    background-color: #5e8ce9;
    color: #fff;
    text-decoration: none; 
}
nav#nav1 li {
    list-style: none;
float: left;}

.DrowDown {
         display: block;
    position: absolute;
    margin: 0;
    padding: 0;
float: none;
}
nav#nav1 li:hover li {
    float: none; }

nav#nav1 li:hover li a {
    background-color: #69f;
    border-bottom: 1px solid #fff;
    color: #000; }
#navbar li li a:hover {
    background-color: #8db3ff; }

nav#nav1  ul li a:hover { background: #686868 ; }
nav#nav1  ul li a:active { background: #F0F0F0; }

下拉列表的JavaScript函数:

function DropDown2() {
var t = document.getElementById("Droplist2");
t.className = "DropDown";
}
function DropDown1() {
var t = document.getElementById("Droplist1");
t.className = "DropDown";
}

function DropUp2() {
var t = document.getElementById("Droplist2");
t.className = "DropUp";
}

function DropUp1() {
var t = document.getElementById("Droplist1");
t.className = "DropUp";
}

如果你想知道我为什么选择这么困难的路线制作导航栏,那是因为我必须使用JavaScript。

这是JS小提琴示例:http://jsfiddle.net/fNPvf/10015/

小提琴中的窗口很小,效果略有不同,但请注意当您将鼠标悬停在“数据验证”上时,下拉菜单会将文本/图像/正文向下推?

1 个答案:

答案 0 :(得分:0)

对于包含<div><ul>本身,您需要绝对定位和更高的 z-index 。只需将其添加到您的代码中,然后根据需要调整z-index

nav#nav1 ul{ 
    position: absolute;
    top: 0;
    z-index: 9;
}

See working demo here