2017-06-01 46 views
0

我有一個元素彈出在頁面加載屏幕上,它隱藏5秒後。我試圖創建邏輯,如果用戶不與彈出窗口交互,將隱藏它,並且如果用戶確實進行了交互,它將保持顯示,並且如果用戶離開元素,計時器將再次開始隱藏。當沒有交互發生時jQuery隱藏元素

<div id="popup"> 
    Some popup 
    <input type="email" placeholder="enter email" /> 
</div> 

<div id="popup-button" style="display:none;"> 
    button to open the popup 
</div> 

// on load, 5 seconds starts 
var goTimeout = setTimeout(function(){ 
    $('#popup').css("display","none"); 
    $('#popup-button').css("display","block"); 
    }, 5000); 
    goTimeout; 


// when mouse enter's popup element and/or user types in input 
// should turn off the setTimeout 
$(document).on("touchstart click mouseenter keyup", "#popup", function(e){ 
    e.stopPropagation(); 
    e.preventDefault(); 
    console.log(e); 
    clearTimeout(goTimeout); 
}); 


// when user mouse leave's the popup the timer starts again, but 
// if user is still focused within input field, don't start until 
// user clicks outside of the element 
$(document).on("mouseleave", "#popup", function(e){ 
    e.stopPropagation(); 
    e.preventDefault(); 
    console.log(e); 
    clearTimeout(goTimeout); 
    goTimeout; 
}); 

想知道如果有人能幫助我的邏輯,沒有得到它的工作,我喜歡

+0

如果每個用戶交互啓動一個新的goTimeout函數並將其增加5秒或什麼?我敢肯定,如果我讓自己清楚,但我希望你得到它 –

+0

goTimeout; - > goTimeout(); –

+1

所以,你已經基本明白了,除了你的代碼中'goTimeout'是一個數字,而不是一個函數。你可能想使用'function hideAfterFive(){return setTimeout(...); }'然後'goTimeout = hideAfterFive();'只要你想再次開始超時。 –

回答

1

goTimer不是一個函數,但你試圖調用它喜歡它是一個在你的鼠標離開節的末尾。創建一個函數來創建/啓動計時器,你將會很開心。就像這樣:

var goTimeout; 
function myTimer() { 
    goTimeout = setTimeout(function() { 
    $('#popup').css("display", "none"); 
    $('#popup-button').css("display", "block"); 
    }, 5000); 
} 
myTimer(); 

然後,只需改變你的鼠標離開一節的最後一行是:的

myTimer();代替goTimeout;

這裏有一個JSFiddle退房。

+0

謝謝,這幫了我。 – hellomello

0

您可以使用DOM元素,如的onmouseover,onmousedown事件的方式,等等。

而且,在最後聲明的超時似乎是錯誤,它更像是一個變量或計數,而不是函數。

你可以有這樣的事情,

Gotimeout=5; 
clearTimeout(goTimeout);