使用 Javascript if 语句通过 OnMouseOut 防止 div 消失
在我正在处理的这个导航栏中,当您将鼠标悬停在按钮上时,我会出现一个 div,当您将鼠标移出按钮时,它会消失。问题是,当我将鼠标移出按钮并向下移动到出现的 div 时,我不希望该 div 消失,因为它包含链接。我希望它仅在我将鼠标移出按钮(而不是出现的 div 上)并移出出现的 div 时消失。
我为此使用 OnMouseOver 和 OnMouseOut 函数。
我应该在 else 语句中使用 if 语句吗?这将允许我做我正在寻找的事情(如上所述)?
JavaScript:
function showlayer(layer){
var myLayer = document.getElementById(layer);
if(myLayer.style.display=="none" || myLayer.style.display==""){
myLayer.style.display="block";
} else {
myLayer.style.display="none";
}
}
HTML:
<div id="topBar">
<div id="navContainer">
(...)
<a href="#" class="nav" onmouseover="javascript:showlayer('commLinks')" onmouseout="javascript:showlayer('commLinks')"><div class="communityBtn">Community</div></a>
<div id="subnavLayer">
<div class="commHidden" id="commLinks">
<div class="commLinksText">Booster Club</div>
<div class="commLinksText">PTO</div>
<div class="commLinksText">Fine Arts</div>
<div class="commLinksText">City of West Branch</div>
</div>
In this nav bar I'm working on, I have a div appear when you mouse over a button and it disappears when you mouse out of it. Problem is, when I mouse out of the button and move down into the appearing div, I don't want the div to disappear since it contains links. I want it to only disappear when I mouse out of the button (not onto the appearing div) and out of the appearing div.
I'm using the OnMouseOver and OnMouseOut functions for this.
What if statement do I use inside the else statement that will allow me to do what I'm looking for (as described above)?
The javascript:
function showlayer(layer){
var myLayer = document.getElementById(layer);
if(myLayer.style.display=="none" || myLayer.style.display==""){
myLayer.style.display="block";
} else {
myLayer.style.display="none";
}
}
The HTML:
<div id="topBar">
<div id="navContainer">
(...)
<a href="#" class="nav" onmouseover="javascript:showlayer('commLinks')" onmouseout="javascript:showlayer('commLinks')"><div class="communityBtn">Community</div></a>
<div id="subnavLayer">
<div class="commHidden" id="commLinks">
<div class="commLinksText">Booster Club</div>
<div class="commLinksText">PTO</div>
<div class="commLinksText">Fine Arts</div>
<div class="commLinksText">City of West Branch</div>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为人们通常通过使弹出导航成为标题的子节点来完成此类事情。这样,当用户将鼠标悬停在弹出窗口的选项上时,从技术上讲,鼠标仍然位于标题内,并且不会触发 mouseout 事件。
以这种方式构建 HTML 的最佳部分是,您实际上可以获得仅包含 CSS 而根本不需要脚本的弹出窗口。基本上你的风格看起来像这样:
I think people usually accomplish this sort of thing by making the popup nav be a child node of the heading. That way when the user mouses over the popup's options, the mouse is still technically inside the heading and doesn't trigger the mouseout event.
The best part of structuring your HTML this way is that you can actually get a popup with only CSS and no script at all. Basically you'd have a style looking something like this: