博客列表 >localstorage刷新背景页面不变色

localstorage刷新背景页面不变色

AA明众科技
AA明众科技原创
2021年11月24日 23:36:18446浏览
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>Document</title>
  8. </head>
  9. <style>
  10. ul {
  11. width: 500px;
  12. height: 150px;
  13. margin: 100px auto;
  14. display: block;
  15. }
  16. li {
  17. list-style: none;
  18. float: left;
  19. padding: 15px;
  20. border: 1px solid #ccc;
  21. margin-left: 20px;
  22. cursor: pointer;
  23. border-radius: 5px;
  24. }
  25. .red {
  26. background-color: red;
  27. }
  28. .yellow {
  29. background-color: yellow;
  30. }
  31. .green {
  32. background-color: green;
  33. }
  34. h2{
  35. margin-top: 100px;
  36. text-align: center;
  37. }
  38. </style>
  39. <body>
  40. <h2>使用localstorage刷新页面背景不变色</h2>
  41. <ul >
  42. <li>更换红色背景</li>
  43. <li>更换黄色背景</li>
  44. <li>更换绿色背景</li>
  45. </ul>
  46. <script>
  47. let arr = ["red", "yellow", "green"];
  48. let ul = document.querySelector("ul");
  49. let lis = ul.querySelectorAll("li");
  50. for (let i = 0; i < lis.length; i++) {
  51. lis[0].onclick = function () {
  52. document.body.style.backgroundColor = arr[0];
  53. window.localStorage.setItem("bgcolor", arr[0]);
  54. };
  55. lis[1].onclick = function () {
  56. document.body.style.backgroundColor = arr[1];
  57. window.localStorage.setItem("bgcolor", arr[1]);
  58. };
  59. lis[2].onclick = function () {
  60. document.body.style.backgroundColor = arr[2];
  61. window.localStorage.setItem("bgcolor", arr[2]);
  62. };
  63. }
  64. window.onload =function(){
  65. document.body.style.backgroundColor = localStorage.getItem('bgcolor')
  66. }
  67. </script>
  68. </body>
  69. </html>
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议