我有一个 iFrame,它在单击按钮时切换为可见或隐藏。我正在使用 JQuery .toggle 函数来执行此操作。目前该区域的 div 默认通过 CSS 隐藏:style="display:none"
新要求要求保存用户最近的显示或隐藏(选定的切换状态)以供下一次页面加载,因此如果他们上次在主页上选择显示 iFrame,下次他们访问时,它将默认可见。我想用 cookie 设置最后选择的切换状态,但我无法让它工作。下面是我的代码:
<meta charset="utf-8">
<title>drop demo</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<style>
#toggle {
width: 100px;
height: 100px;
background: #ccc;
}
.button {
padding-top: 10px;
padding-right: 20px;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<button type="button" id="button"
title="Personalized Sales Dashboard">Show/Hide</button>
<div id="toggle" style="display:none" frameborder="2">
<iframe src="https://sample.com"="" id="myfr" scrolling="no" frameborder="0"
height="800px" width="100%">Your Browser Do not Support Iframe</iframe>
</div>
<script>
$("#button").click(function () {
$("#toggle").toggle("blind");
});
$(function () {
$("#button").tooltip();
});
</script>
最佳答案
在你的按钮上设置一个 cookie 点击 div 是否可见:
document.cookie = "toggleState=" + $("#toggle").is(':visible');
并在页面加载时检索它,相应地显示或隐藏内容:
var toggleState = document.cookie.replace(/(?:(?:^|.*;\s*)toggleState\s*\=\s*([^;]*).*$)|^.*$/, "$1");
if (toggleState == 'true') {
$("#toggle").show();
}
else {
$("#toggle").hide();
}
https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
关于javascript - 使用 Cookie 保存 JQuery 切换状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22967444/