【问题标题】:I want the CSS of a page to change when a button is clicked我希望在单击按钮时更改页面的 CSS
【发布时间】:2020-02-15 14:30:57
【问题描述】:

我发现了如何使用单个元素执行此操作,但我找不到任何可以更改页面正文 CSS 的内容。我正在尝试做一个东西,当你点击按钮时它会在明暗模式之间切换。

<!DOCTYPE html>
<button style="background-color: #252525;
border: 2px;
border-style: solid;
border-color: white;
color: white; 
padding: 10px 32px;
text-align: center;
text-decoration: none; 
display: inline-block;
font-size: 16px;  
font-weight: bold;
margin: 4px 2px;
cursor: pointer;" id="changethemebutton" onclick="changeTheme()">Change Theme</button>

function changeTheme() {
document.getElementById(".background").style.background = "black";
}
</script>
<style>
body{
    background-color:white
}
</style>

【问题讨论】:

标签: javascript html css innerhtml


【解决方案1】:

在您的网站上设置暗模式的最佳方法是使用 javascript 在您的身体上切换 .dark-mode 类,然后使用 css 对其进行样式化:

body {
  /* light-mode styles */
  background-color: white;
}

body.dark-mode {
  /* dark-mode styles */
  background-color: black;
}
<button style="background-color: #252525;
border: 2px;
border-style: solid;
border-color: white;
color: white; 
padding: 10px 32px;
text-align: center;
text-decoration: none; 
display: inline-block;
font-size: 16px;  
font-weight: bold;
margin: 4px 2px;
cursor: pointer;" id="changethemebutton" onclick="changeTheme()">Change Theme
</button>

<script>
  function changeTheme() {
    document.body.classList.toggle('dark-mode');  // <-- Toogle dark-mode class to <body>
  }
</script>

【讨论】:

    【解决方案2】:

    您正在尝试使用不正确的方法来定位具有类的元素。 getElementById 以指定 id 为目标。如果你想定位一个类,最理想的方法是querySelector

    document.querySelector(".background").style.background = "black";
    

    【讨论】:

      猜你喜欢
      • 2012-09-08
      • 2017-04-28
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多