【发布时间】:2018-05-17 21:42:51
【问题描述】:
我想随时更改 div 的类,不管它有什么类。如果 div 有“mystyle”类,我希望它变成“mystyle1”,反之亦然。我的代码是这样的:
<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
width: 300px;
height: 50px;
background-color: coral;
color: white;
font-size: 25px;
}
.mystyle1 {
width: 100px;
height: 100px;
background-color: black;
color: coral;
font-size: 30px;
}
</style>
</head>
<body>
<p>Click the button to change the style class from DIV.</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV" class="mystyle">
I am a DIV element
</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.classList.contains("mysyle")) {
x.classList.replace("mystyle", "mystyle1");
} if (x.classList.contains("mysyle1")) {
x.classList.replace("mystyle1", "mystyle");
}
}
</script>
</body>
</html>
当我们按下按钮时,它必须随时更改 css 样式。但事实并非如此。 我认为问题与条件(classList.contains)和classList.replace的混合有关,因为我是单独做的并且它有效。
你知道我的问题是什么吗?谢谢。
【问题讨论】:
-
你在这里拼错了 :if (x.classList.contains("mysyle")) { x.classList.replace("mystyle", "mystyle1"); } if (x.classList.contains("mysyle1")) { x.classList.replace("mystyle1", "mystyle"); }
-
现在试试,我刚刚更正了它
标签: javascript html css replace contains