我有一个隐藏和显示html div的按钮
<button id="hideshow" title="Click to Show/Hide Assessment"></button>
这是脚本
$(document).ready(function(){ /// hide and show button
$('#hideshow').click(function() {
$('#containerDiv1').toggle("slideLeft");
$("i", this).toggleClass("fas fa-lg fa-chevron-up fas fa-lg fa-chevron-down");
});
});
现在我要实现的是,当用户选择隐藏div并单击按钮时,当他重新加载页面时,它应该仍然隐藏。因为默认情况下,当我打开网页时,我的div才会显示。
有帮助吗?
答案 0 :(得分:4)
使用sessionStorage
,localStorage
或cookie
来保持状态,然后在页面加载时检索并恢复它。这确实需要做一些工作,但是UI的闪烁是免费的;)
这显示了原理:
$(document).ready(function(){ /// hide and show button
const containerState = localStorage.getItem('containerDiv1');
switch (containerState) {
case 'visible':
// your code for when the user last saw it "visible"
break;
case 'hidden':
// your code for when the user last saw it "hidden"
break;
default:
// any action that should take place when containerState is empty (not set, never clicked)
}
$('#hideshow').click(function() {
$('#containerDiv1').toggle("slideLeft");
$("i", this).toggleClass("fas fa-lg fa-chevron-up fas fa-lg fa-chevron-down");
// on every click, store the current visibility state in localStorage
localStorage.setItem('containerDiv1', $('#containerDiv1:visible').length ? 'visible' : 'hidden');
});
});
答案 1 :(得分:0)
按照connexo的答案
$('#containerDiv1").css('display')=== 'none' ? 'hidden' : ' visible'
应该工作