我想随时改变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的混合有关,因为我单独做了它并且它工作。
你知道这是我的问题吗?谢谢。
一些事情:
mystyle
;<!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("mystyle")) {
x.classList.replace("mystyle", "mystyle1");
} else if (x.classList.contains("mystyle1")) {
x.classList.replace("mystyle1", "mystyle");
}
}
</script>
</body>
</html>
这是你的代码..
<!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");
/*Here you missspelled "mystyle"*/
if (x.classList.contains("mystyle")) {
x.classList.replace("mystyle", "mystyle1");
} else if (x.classList.contains("mystyle1")) {
x.classList.replace("mystyle1", "mystyle");
}
}
</script>
</body>
</html>
我不确定您使用的浏览器,但我注意到Internet Explorer在classList.replace方面存在问题。对我有用的是逐个删除和添加类。
干杯!