2016-11-28 150 views
3

當鼠標離開屏幕時,將顯示以下彈出窗口。我需要一個cookie或者一些東西來顯示這一次(我是一個新手),但是無法弄清楚如何將它加入到代碼中。JQuery - 僅顯示彈出窗口一次

// Exit intent 
function addEvent(obj, evt, fn) { 
    if (obj.addEventListener) { 
     obj.addEventListener(evt, fn, false); 
    } 
    else if (obj.attachEvent) { 
     obj.attachEvent("on" + evt, fn); 
    } 
} 

// Exit intent trigger 
addEvent(document, 'mouseout', function(evt) { 
    if (evt.toElement == null && evt.relatedTarget == null) { 
     $('.lightbox').slideDown(); 
    }; 
}); 

// Closing the Popup Box 
$(document).ready(function(){ 
    $('#close').click(function(){ 
     $('.lightbox').slideUp(); 
    }); 
}); 

您可以在這裏的行動查看代碼:http://championcontainersnz.com/buy_estimate

任何幫助,您可以提供將不勝感激。謝謝。

+0

沒有餅乾。只需創建一個全局變量'var hasLeftScreen = false;',然後在第一次離開時將其設置爲true。將這個條件添加到你的ifs中。 – nurdyguy

+0

你是否想再次展示它或者僅僅在該頁面上展示? – Yatrix

+0

當彈出窗口顯示時,創建一個cookie,稍後檢查cookie是否存在。 – Aleksandar

回答

3

下面的例子將告訴你與你所提供的代碼。你只需要一個變量來存儲盒子是否彈出。

var isPopped = false; 
 
// Exit intent 
 
function addEvent(obj, evt, fn) { 
 
    if (obj.addEventListener) { 
 
    obj.addEventListener(evt, fn, false); 
 
    } else if (obj.attachEvent) { 
 
    obj.attachEvent("on" + evt, fn); 
 
    } 
 
} 
 

 
// Exit intent trigger 
 
addEvent(document, 'mouseout', function(evt) { 
 
    if (evt.toElement == null && evt.relatedTarget == null && isPopped == false) { 
 
    $('.lightbox').slideDown(); 
 
    isPopped = true; 
 
    }; 
 
}); 
 

 
// Closing the Popup Box 
 
$(document).ready(function() { 
 
    $('#close').click(function() { 
 
    $('.lightbox').slideUp(); 
 
    }); 
 
});
.lightbox { 
 
    border: solid 1px #000; 
 
    padding: 50px; 
 
    position: absolute; 
 
    top: 50px; 
 
    left: 150px; 
 
    display: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="lightbox">Hello There 
 
<button id="close">Close Me</button></div>

+1

傑出的傑森。有用!非常感謝您花時間提供此答案。簡單但有效。做得好。 – N00b

+0

@ N00b謝謝:) – CodeLikeBeaker

1

我不是jQuery的專家,但解決方案可能與創建窗口變量一樣簡單。

定義這個initally,函數外:

window.hasPoppedUp = false; 

在彈出代碼:

if(!window.hasPoppedUp) { 
    //do stuff 
    window.hasPoppedUp = true; 
} 
+0

謝謝哈利。對不起,我很痛苦,但我怎麼可能將這段代碼合併到我的原始代碼? – N00b

相關問題