Blogger Information
Blog 7
fans 0
comment 0
visits 3285
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
localStorage实现本地存储读取CSS样式
凝思
Original
551 people have browsed it

localStorage本地存储读取样式

第一个设置样式页面

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns="http://www.w3.org/1999/html">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>这是第一个页面 用户设置 users.html</title>
  6. </head>
  7. <body>
  8. <script>
  9. // localStorage 本地储存网页背景、字体颜色
  10. function setBgColor() {
  11. var color = window.prompt("请输入背景颜色");
  12. localStorage.setItem('bgcolor', color);
  13. }
  14. function setFontColor(color) {
  15. color = window.prompt("请输入字体颜色");
  16. localStorage.setItem('fontcolor', color);
  17. }
  18. </script>
  19. <div align="center">
  20. <br><br><br><br><br><br><br><br><h1>第一个设置页面<br><br><input type="button" onclick="setBgColor()" value="设置首页背景色">
  21. <input type="button" onclick="setFontColor()" value="设置首页字体色"><br><br>
  22. <a href="index.html">进去首页</a></h1>
  23. </div>
  24. </body>
  25. </html>

设置样式效果图

设置样式效果图

第二个页面 index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>这是第二个页面 进入首页 index.html</title>
  6. <style id="css"></style>
  7. </head>
  8. <body>
  9. <script>
  10. window.onload=function(){
  11. var bgcolor= localStorage.getItem('bgcolor');
  12. var fontcolor = localStorage.getItem('fontcolor');
  13. var sto = document.getElementById('css');
  14. console.log(bgcolor);
  15. sto.innerText=' * {background-color:'+bgcolor+';color:'+fontcolor+';}';
  16. }
  17. </script>
  18. <div align="center">
  19. <br><br><br><br><br><br><br><br>
  20. <h1>第二个页面样式</h1>
  21. <br>
  22. <h2>关闭浏览器当前页面,下次重新进入会保留上次的样式设置</h2>
  23. <h1><a href="users.html">返回设置页面</a>
  24. <a href="index.html" onclick="window.localStorage.clear();">清除页面样式</a></h1>
  25. </div>
  26. </body>
  27. </html>

设置后效果图

设置后效果图

知识点小结

var color = window.prompt(“请输入背景颜色”); //声明变量存储数据
localStorage.setItem(‘bgcolor’, color); //将变量color存储到bgcolor字段

var bgcolor= localStorage.getItem(‘bgcolor’);//第二个页面读取
window.localStorage.clear(); //清除页面样式

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post