[英]How can i keep a popup div always open, even on page refresh/reload until a user close it using HTML5 local storage
我使用以下代碼使用 jquery toggle
顯示/隱藏 div。 我試圖找到一種方法,以便瀏覽器可以記住彈出 div 的最后狀態。 我想要的是即使在頁面刷新/重新加載時也保持這個 div 始終打開,直到用戶關閉它。 我認為我必須使用 html5 web 存儲和 js,但我不知道如何將它應用於我的代碼。
這是代碼:
$(".menu-btn").click(function(event) { event.stopPropagation(); $(".menu-window").toggle(); });
.menu-btn { background:#0088cc; color:#fff; font-size:11px; padding:8px; text-align:center; width:150px; border-radius:5px; font-weight:600; cursor:pointer; }.menu-window { background:#ccc; width:300px; margin-top:10px; padding:40px; text-align:center; border-radius:4px; display:none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <div class="menu-btn">MENU</div> <div class="menu-window"> I AM A POPUP WINDOW </div>
任何幫助將不勝感激。
您可以使用 localStorage
jQuery(".menu-btn").click(function(event) {
event.stopPropagation();
if (jQuery(".menu-window").is(':visible')) {
jQuery(".menu-window").hide();
localStorage.setItem("modalFlag", 'false');
}
else
{
jQuery(".menu-window").show();
localStorage.setItem("modalFlag", 'true');
}
});
jQuery(window).on('load',function(){
if (localStorage.getItem("modalFlag") == 'true') {
jQuery(".menu-window").show();
}
if (localStorage.getItem("modalFlag") == 'false') {
jQuery(".menu-window").hide();
}
});
嗨,也許這會有所幫助,我對其進行了測試並完成了工作
// check if there a key store with state of dialog
$(document).ready(function(){
// get the value stored
var isOpen = sessionStorage.getItem("opened");
if (isOpen === "yes") {
// if the last value saved was yes so show the dialog
$(".menu-window").show();
}
});
$(".menu-btn").click(function(event) {
event.stopPropagation();
$(".menu-window").toggle(function() {
// get the last value saved and inverts the value
var isOpen = sessionStorage.getItem("opened");
if (isOpen && isOpen === "no") {
sessionStorage.setItem("opened", "yes");
} else {
sessionStorage.setItem("opened", "no");
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.