javascript - 切换一次更改 2 个 DIV 宽度 + localStorage
问题描述
function myFunction() {
var element = document.getElementById("one1");
element.classList.toggle("one2");
var element = document.getElementById("two1");
element.classList.toggle("two2");
}
<style>
#section{margin-left:50px;
margin-right:50px
}
#monbouton{float:right;
font-size:25px;
width:50px;
height:50px;
background-color:#F1F1F1;
border:1px solid ##F1F1F1
}
#one1{
float:left;
width:40%;
height:100px;
border:1px solid blue
}
.one2{
width:10% !important;
height:200px;
border:1px solid red !important;
}
.one2 #afairedisparaitre{display:none
}
#two1{float:right;
width:59%;
height:100px;
border:1px solid green
}
.two2{width:89% !important
}
</style>
<!DOCTYPE html>
<html>
<body>
<div id="section">
<div id="one1">
<button id="monbouton" onclick="myFunction()">↔</button>
<div id="afairedisparaitre">This is DIV #one1<br />
Button toggle to CLASS .one2<br />
and reverse</div>
</div>
<div id="two1">This is DIV #two1<br />
Button toggle to CLASS .two2<br />
and reverse</div>
</div>
</body>
</html>
我正在尝试缩小我网站的左侧,以便用户觉得更舒适时可以拥有更宽的右侧。我缺少的是一种在加载其他页面时可以在整个站点上保留选择的方法,直到用户再次单击为止。也许解决方案是在 "localStorage" 的 js 中多写几行?我真的很感激任何帮助。
解决方案
当然。只需创建一个 localStorage 变量来跟踪收缩是否应该处于活动状态,并使用它在页面加载或类似的东西上应用您的样式。
function shrinkActive() {
var shrink;
if (!(shrink = localStorage.getItem("shrink"))) {
localStorage.setItem("shrink", "false");
return false;
}
return JSON.parse(shrink);
}
function setShrink(active) {
var element1 = document.getElementById("one1");
var element2 = document.getElementById("two1");
if (active) {
element1.classList.add("one2");
element2.classList.add("two2");
} else {
element1.classList.remove("one2");
element2.classList.remove("two2");
}
localStorage.setItem("shrink", active.toString());
}
function myFunction() {
setShrink(!shrinkActive());
}
window.onload = function() {
setShrink(shrinkActive());
}
链接到工作的 Codepen。https://codepen.io/bugcatcher9000/pen/pogZbrz?editors=1111
推荐阅读
- parsing - LL 自顶向下解析器,从 CST 到 AST
- git - 应用程序构建中添加的当前分支的 Fastlane git 提交
- angular - 将 Bootstrap 4 添加到 Angular 6 或 Angular 7 应用程序
- amazon-web-services - AWS,如何准备因推送通知而导致的用户高峰?
- java - 如何从服务器获取回声
- sql - 合并查询 1 和查询 2 的结果,其中查询 2 中只有一列应该出现
- jquery - ASP.NET MVC5,重定向后如何保存表单状态以检索它?
- node.js - 由于可能与节点冲突,节点预gyp安装错误
- java - 如何从运行时构建的上下文中恢复状态机?
- asynchronous - 异步/等待函数中的 Expect.assertions