[英]How to make dropdown menu disappear after a certain amount of time JavaScript
當您將鼠標懸停在標記中的“第一節”上時,我會看到一個下拉菜單。 我想知道如何獲取JavaScript代碼以重復自身,以檢查在一定時間后列表再次處於什么狀態,以便菜單關閉。 誰能幫幫我嗎?
的HTML
<div class = "sidebarwrap">
<ul>
<li>
<a href="#" onmouseover="toggle(this); return true;" onmouseout="timer()">Section One</a>
<ul>
<li><a href="#" >link page</a></li>
<li><a href="#" >link page</a></li>
<li><a href="#" >link page</a></li>
<li><a href="#" >link page</a></li>
</ul>
</li>
</ul>
</div>
的CSS
.sidebarwrap{
width:auto;
height:auto;
}
.sidebarwrap ul{
float:left;
display:block;
background:white;
padding:10px;
margin-right:30px;
margin-left:10px;
list-style-type:none;
border:1px dotted #0099CC;
border-radius:100px/10px;
}
.sidebarwrap ul ul{
list-style-type:none;
display:none;
border:0px dotted #0099CC;
border-radius:20px/60px;
}
.sidebarwrap li li{
list-style-type:circle;
border:0px dotted #0099CC;
border-radius:20px/60px;
padding:5px;
}
的JavaScript
var cssNode = document.createElement('link');
cssNode.setAttribute('rel','stylesheet');
cssNode.setAttribute('type','text/css');
cssNode.setAttribute('href', 'javascript-overrides.css');
document.getElementsByTagName('head') [0].appendChild(cssNode);
function toggle(toggler) {
if(document.getElementById){
targetElement = toggler.nextSibling;
if(targetElement.className == undefined){
targetElement = toggler.nextSibling.nextSibling;
}
if (targetElement.style.display == "block")
{
targetElement.style.display = "none";
}
else
{
targetElement.style.display = "block";
timer();
}
}
}
function timer(){
var Time = setTimeout(function(){toggle(toggler)},1000);
}
您可以使用jQuery中的.hover()方法執行此操作。 只需在頁面加載時綁定到鏈接。
$(document).ready(function () {
$("a").hover(function () {
$(this).next().slideDown();
},
function () {
$(this).next().delay(1000).slideUp();
});
});
參見工作示例: http : //jsfiddle.net/WFN6q/
這是Vanilla JS中的一個工作示例:
<ul>
<li>
<a href="#" onmouseover="showMenu(this)" onmouseout="hideMenu(this)">Section One </a>
<ul>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
</li>
</ul>
對應的JS:
function showMenu(myLink) {
myLink.nextElementSibling.style.display = 'block';
}
function hideMenu(myLink) {
var ulElem = myLink.nextElementSibling;
if (ulElement.style.display === 'block') {
setTimeout(function () { myLink.nextElementSibling.style.display = 'none' }, 1000);
}
}
我注意到,在你的代碼,你的onmouseout設置為來電計時器(),這將創建一個沒有外來超時功能toggler
定義。 此外,您的代碼將無限期地(每1000毫秒)求助。
您應該定義一個全局Timers變量來保存您的計時器引用。 這樣,該功能可以退出,您可以取消或以其他方式操作計時器。 同樣,您可以在此處實現Singleton模型,並避免使用很多計時器。
var Timers = {}; // create a Timers object to hold our timers.
function timer(target){
Timers.sectionOne = setTimeout(function(){ toggle(target); }, 1000);
}
編輯:除了方法@Bic所描述的之外,我還會考慮這一點,這非常好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.