【问题标题】:How to change the body background-color of all web site pages with JavaScript?如何使用 JavaScript 更改所有网站页面的正文背景颜色?
【发布时间】:2019-08-22 19:12:44
【问题描述】:

简而言之,我有一个网站 http://myWebSite,其中包含两个页面 page1.htmlpage2.html
我在 page1.html 和 page2.html 的 head 部分使用了 CSS 样式表

<link crossorigin="anonymous" rel="stylesheet" href="myStyles.css">

myStyles.css:

body {
  background-color: blue;
}

在 page1.html 上,我使用以下 JavaScript 代码修改当前页面的背景颜色:

<script>
document.styleSheets[0].cssRules[0].style.backgroundColor="white";
</script>

正如预期的那样,只有 page1.html 的背景颜色发生了变化。 如何为所有网站页面保留此修改?我想我必须使用cookies。正确的 ?我该怎么做?
感谢您的回答。

【问题讨论】:

  • 为什么要用JS改?为什么不直接更改 CSS 文件中的颜色?如果你要在 JS 中改变它,你为什么要修改样式表本身而不是直接 document.body.style.backgroundColor 呢?我不明白你想在这里做什么。
  • @IceMetalPunk。这是我的问题的简要总结。我想创建一个页面来改变我的页面样式。
  • @Stef1611 我们了解问题以及您当前的解决方案。但是想知道 why 那么,为什么用户需要这个功能。 这是给谁的?它可以帮助更好地塑造答案。

标签: javascript html css


【解决方案1】:

设置 cookie 可以工作。一个更好/更广泛的解决方案是使用LocalStorage。这样,更改将出现在任何 Web 浏览器中。如果您是 W3Schools 上的新手,那么有一个使用 LocalStorage 的好例子:https://www.w3schools.com/html/html5_webstorage.asp

根据我的代码,我有

    if (typeof Storage !== 'undefined') {
      if (localStorage) localStorage.setItem('bodyclass', color);
    }

try {
    var bodyClass = localStorage.getItem('bodyclass');
    if (bodyClass) $(document.body).addClass(bodyClass);
  }
catch (e) {
  error.reportError("No local storage support. Changes to body style will not be persistant");
}

【讨论】:

  • 感谢您的回答。 LocalStorage 似乎是一个很好的解决方案。但是如果我想在我来到站点时保留这个修改,它可以工作吗?
  • @Stef1611 如果您正确使用 LocalStorage,可能保留您的修改。请注意,这些修改仅适用于存储它们的计算机。
【解决方案2】:

无需使用 cookie(cookie 对服务器有用,而不是对浏览器有用)。 使用localStorage将当前背景色保存到本地。

<!-- page1.html -->
<script>
document.styleSheets[0].cssRules[0].style.backgroundColor="white";
localStorage.backgroundColor = "white";
</script>

在 page2.html 中,您必须从 localStorage 获取属性并使用它设置背景。

<!-- page2.html -->
<script>
var color = localStorage.backgroundColor;
if(color) {
  document.styleSheets[0].cssRules[0].style.backgroundColor = color;
}
</script>

【讨论】:

    【解决方案3】:
    document.getElementsByTagName("BODY")[0].setAttribute("style", "color:red; border: 1px solid blue;")
    

    https://jsfiddle.net/d39brzLk/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 1970-01-01
      • 2015-08-29
      • 2010-09-16
      • 2018-02-21
      相关资源
      最近更新 更多