javascript:将classList替换为条件

问题描述 投票:1回答:3

我想随时改变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的混合有关,因为我单独做了它并且它工作。

你知道这是我的问题吗?谢谢。

javascript html css replace contains
3个回答
1
投票

一些事情:

  1. 你在x.classList.contains()中拼错了mystyle;
  2. 你的第二个if语句应该是else-if。这是因为它更改了类,并再次检查新类,从而重置它。

<!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>

0
投票

这是你的代码..

    <!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>

0
投票

我不确定您使用的浏览器,但我注意到Internet Explorer在classList.replace方面存在问题。对我有用的是逐个删除和添加类。

干杯!

© www.soinside.com 2019 - 2024. All rights reserved.