gpt4 book ai didi

javascript - jQuery toggleClass 不切换类

转载 作者:行者123 更新时间:2023-11-28 13:26:53 25 4
gpt4 key购买 nike

我一直试图通过制作这个简单的脚本来理解toggleClass函数,但它并没有按照我预期的方式工作。

<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<style type="text/css">
body {
font-family: "Kozuka Gothic Pro";
}

.red {
background: red;
}

.blue {
background: blue;
}

div {
width: 200px;
height: 200px;
}

</style>
</head>

<body>
<div class="blue"></div>

<script>
$("div").click(function() {
$(this).toggleClass("red");
});
</script>
</body>

但是,如果我将 div 类更改为红色,并将toggleClass 参数更改为“蓝色”,则它可以工作,有人可以向我解释一下吗?我希望收到你的来信。提前致谢!

最佳答案

您需要在toggleClass函数中添加蓝色和红色类来更改两者,例如,

$("div").click(function() {
$(this).toggleClass("red blue");
});

$("div").click(function() {
$(this).toggleClass("red blue");
});
body {
font-family: "Kozuka Gothic Pro";
}

.red {
background: red;
}

.blue {
background: blue;
}

div {
width: 200px;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="blue"></div>

当您在 togleclass 函数中仅使用红色时会发生什么,它将应用,但由于蓝色类和显示的蓝色背景,更改不会覆盖。因此,如果您希望代码正常工作,那么在这种情况下您需要在 red-background 中使用 !important,例如,

.red {
background: red !important;
}

$("div").click(function() {
$(this).toggleClass("red");
});
body {
font-family: "Kozuka Gothic Pro";
}

.red {
background: red !important;
}

.blue {
background: blue;
}

div {
width: 200px;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="blue"></div>

请注意,我只是通知您(通过第二种选择)为什么您的代码不起作用。你必须选择我的第一个选择。

关于javascript - jQuery toggleClass 不切换类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28470083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com