简体   繁体   English

即使重新加载页面也显示div

[英]show the div even after the page reload

On click of a button, I am showing a div by using 在单击按钮时,我通过使用来显示div

document.getElementById('message-box').style.display="block";

but when the page is reloaded this div disappears again. 但重新加载页面后,该div再次消失。 I want the div to stay until i explicitly close it with x button. 我希望div停留到我用x按钮显式关闭它为止。 How I can do this? 我该怎么做?

I am not going to write code on here, since it makes a developer lazy by copy/pasting, but i am going to tell you how you can solve it. 我不会在此处编写代码,因为它会使开发人员因复制/粘贴而变得懒惰,但是我将告诉您如何解决它。

The issue in here is that, you refresh the page, and the state of that div is removed, since is not a persistent state. 这里的问题是,刷新页面后,该div的状态将被删除,因为它不是持久状态。

A solution for this, is either cookies, or localStorage, where you can set off a variable, if the button is off or not. 一个解决方案是cookie或localStorage,无论按钮是否关闭,您都可以在其中设置变量。

Hope this helps. 希望这可以帮助。

This simple example will do what you want to achieve 这个简单的示例将完成您想要实现的目标

html: HTML:

<div class='hidden' id='hiddenDiv'>NOT SHOWN UNTIL YOU CLICK IT!! <span>
        <input type='button' value='X' onclick='closeClick()'>
    </span>

</div>
<input type='button' value='show me the div' onclick='openClick()' />

JS: JS:

function openClick() {
    document.getElementById('hiddenDiv').style.display = "block";
    sessionStorage.setItem('clicked', true);
}

function closeClick() {
    document.getElementById('hiddenDiv').style.display = "none";
    sessionStorage.removeItem('clicked');
}

window.onload = function () {
    var data = sessionStorage.getItem('clicked');
    if (data == 'true') {
        openClick();
    }
};

fiddle example 小提琴的例子

试试这个:

window.onload = function() {document.getElementById('message-box').style.display="block";};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM