我正在做一个小项目,我的背景色不会改变。
https://codepen.io/JorisMertz/pen/gjmZOa
这是我的Codepen,如果您能帮助我,将不胜感激。
或者这是我的代码:
var container = document.getElementById("container");
function togl() {
if (container.style.background == "#232323") {
container.style.background = "#fafafa";
} else {
container.style.background = "#232323";
}
}
* {
font-family: roboto;
}
#container {
color: #fafafa;
background: #232323;
padding: 20px;
max-width: 60%;
border-radius: 20px;
top: 50%;
left: 50%;
box-shadow: 0px 0px 50px 0px rgba(0, 0, 0, 0.2);
position: absolute;
transform: translate(-50%, -50%);
}
body,
html {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
background: #232323;
}
#toggle {
appearance: none;
border-style: none;
padding: 7px 25px 7px 25px;
position: relative;
left: 50%;
transform: translate(-50%);
outline: none;
cursor: pointer;
}
<div id="container">
<h1>A cool heading</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla faucibus interdum dapibus. Morbi est velit, aliquam ac eros in, aliquet semper tortor. Proin hendrerit ultricies dignissim. Proin suscipit sapien ac eleifend dignissim. Vestibulum sit amet
rutrum mauris. Donec tincidunt sem at sapien auctor, quis rutrum augue luctus. Vivamus elementum non lacus non blandit.</p>
<button id="toggle" onclick="togl()">Toggle</button>
</div>
最佳答案
推荐的方法是切换一个类,并使用addEventListener
代替内联脚本
这很容易维护,您可以将样式放在一个位置,将脚本放在一个位置,将标记放在一个位置。
堆栈片段
var container = document.getElementById("container");
var button = document.getElementById("toggle");
button.addEventListener('click', function(){
container.classList.toggle('toggled');
})
* {
font-family: roboto;
}
#container {
color: #fafafa;
background: #232323;
padding: 20px;
max-width: 60%;
border-radius: 20px;
top: 50%;
left: 50%;
box-shadow: 0px 0px 50px 0px rgba(0, 0, 0, 0.2);
position: absolute;
transform: translate(-50%, -50%);
}
#container.toggled {
background: #fafafa;
color: #232323;
}
body,
html {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
background: #232323;
}
#toggle {
appearance: none;
border-style: none;
padding: 7px 25px 7px 25px;
position: relative;
left: 50%;
transform: translate(-50%);
outline: none;
cursor: pointer;
}
<div id="container">
<h1>A cool heading</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla faucibus interdum dapibus. Morbi est velit, aliquam ac eros in, aliquet semper tortor.</p>
<button id="toggle">Toggle</button>
</div>
关于javascript - 背景颜色不会改变javascript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51481477/