跨多个页面隐藏和显示元素
Hide and Show elements across multiple pages
有没有办法跨多个页面保存元素的状态?也许使用会话或本地存储?
这样的功能是我想要实现的。但我希望它记住退出和返回页面时显示和隐藏的内容。
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
要达到预期结果,请使用以下选项 localStorage 和 onload 函数
使用locaStorage.setItem和localStorage.getItem设置和从localstorage获取值
在body上使用onload函数从本地存储设置显示
function myFunction() {
var x = document.getElementById("myDIV");
console.log(x.style.display)
if (x.style.display === "none") {
localStorage.setItem('display','block')
x.style.display = "block";
} else {
localStorage.setItem('display','none')
x.style.display = "none";
}
console.log(localStorage)
}
function checkDisplay(){
var x = document.getElementById("myDIV");
x.style.display = localStorage.getItem('display');
}
<body onload="checkDisplay()">
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<body>
有没有办法跨多个页面保存元素的状态?也许使用会话或本地存储?
这样的功能是我想要实现的。但我希望它记住退出和返回页面时显示和隐藏的内容。
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
要达到预期结果,请使用以下选项 localStorage 和 onload 函数
使用locaStorage.setItem和localStorage.getItem设置和从localstorage获取值
在body上使用onload函数从本地存储设置显示
function myFunction() {
var x = document.getElementById("myDIV");
console.log(x.style.display)
if (x.style.display === "none") {
localStorage.setItem('display','block')
x.style.display = "block";
} else {
localStorage.setItem('display','none')
x.style.display = "none";
}
console.log(localStorage)
}
function checkDisplay(){
var x = document.getElementById("myDIV");
x.style.display = localStorage.getItem('display');
}
<body onload="checkDisplay()">
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<body>