繁体   English   中英

我希望在单击按钮时更改页面的 CSS

[英]I want the CSS of a page to change when a button is clicked

我找到了如何使用单个元素执行此操作,但找不到任何会更改页面正文 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 在您的身体上切换类.dark-mode ,然后使用 css 对其进行.dark-mode化:

 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>

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM