2012-02-28 76 views
-6

我正在使用mVc 3視圖,當我將鼠標移到div上時彈出來,所以有很多div's 當我將鼠標懸停在其他具有不同值的彈出窗口上時功能正常工作我只是想在沒有調用其他功能的情況下在鼠標上添加延遲1秒處理Javascript dealy 1秒

//Display a named menu, at the position of another object 
function display_menu(parent, named) { 
    //get the named menu 
    var menu_element = document.getElementById(named); 
    //override the 'display:none;' style attribute 
    menu_element.style.display = ""; 
    //get the placement of the element that invoked the menu... 
    var placement = findPos(parent); 
    //...and put the menu there 
    menu_element.style.left = placement[0] + "px"; 
    menu_element.style.top = placement[1] + "px"; 
} 

//Hide a named menu 
function hide_menu(named) { 
    //get the named menu 
    var menu_element = document.getElementById(named); 
    //hide it with a style attribute 
    menu_element.style.display = "none"; 
} 
+4

代碼轉儲並不嘗試隔離問題。 – leppie 2012-02-28 05:57:26

回答

1

添加超時。首先創建一個變量在頂部保持計時器,就像這樣:

var timeout = null; 

然後更新display_menu家長對超時工作(我的代碼中的註釋說明):

function display_menu(parent, named) { 
    // First clear any existing timeout, if there is one 
    if (timeout) clearTimeout(timeout); 

    // Set a timeout to open the menu after 1 second 
    timeout = setTimeout(function() { 
     // As we open the menu, the timer went off, so clear the timeout variable 
     timeout = null; 

     //get the named menu 
     var menu_element = document.getElementById(named); 
     //override the 'display:none;' style attribute 
     menu_element.style.display = ""; 
     //get the placement of the element that invoked the menu... 
     var placement = findPos(parent); 
     //...and put the menu there 
     menu_element.style.left = placement[0] + "px"; 
     menu_element.style.top = placement[1] + "px"; 
    }, 1000); 
} 

最後, hide_menu的邏輯:

function hide_menu(named) { 
    // If a timer is running to open a menu... 
    if (timeout) { 
     // Nothing has yet been opened, so just stop the timer 
     clearTimeout(timeout); 
     timeout = null; 
    // If there isn't a timer running, it's because we displayed a menu; hide it here 
    } else { 
     //get the named menu 
     var menu_element = document.getElementById(named); 
     //hide it with a style attribute 
     menu_element.style.display = "none"; 
    } 
}