gpt4 book ai didi

javascript - JQuery:当样式表选择器更具体时,如何使用 addClass 更改属性?

转载 作者:行者123 更新时间:2023-11-28 01:10:59 26 4
gpt4 key购买 nike

通过某些样式表,可以专门选择一个标签并设置其样式。通过使用 JQuery 添加一个类,我想重写一个属性。但是,样式表选择器更具体,因此添加的类的属性无效。在这种情况下,如何使用 JQuery 调整属性?

在代码片段中,红色文本应变为蓝色。但它保持红色。

应该用addClass来解决

$(document).ready(function(){
$("button").click(function(){
$("p:first").addClass("hero");
});
});
p:nth-of-type(1) {
color: red;
}

.intro {
font-size: 150%;
color: red;
}

.hero {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>This is a heading</h1>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Add a class name to the first p element</button>

最佳答案

只需将 :not(.hero) 添加到 p:nth-of-type(1) 行就可以了!

这样,只有当第一个 p 没有职业英雄时,你才会设置红色

$(document).ready(function(){
$("button").click(function(){
$("p:first").addClass("hero");
});
});
p:nth-of-type(1):not(.hero) {
color: red;
}

.intro {
font-size: 150%;
color: red;
}

.hero {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>This is a heading</h1>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Add a class name to the first p element</button>

关于javascript - JQuery:当样式表选择器更具体时,如何使用 addClass 更改属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52101550/

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