如果< p>已定义css样式,则使用JS更改文本颜色样式

qaxu7uf2  于 2022-12-15  发布在  其他
关注(0)|答案(4)|浏览(157)

p tag在css中已经定义了颜色样式时,使用JS不能改变文本颜色

var prelearnBtn = document.getElementById("copyto");
prelearnBtn.addEventListener("click", function() {
  setTimeout(function() {
    document.getElementById("quotedes").style.color = "blue";
  }, 100);
});
p {
  color: green;
  font-size: 25px;
}
<code class="quotedes" id="quotedes">
    <p>Hello</p>
 </code>
<p>default text </p>
<button id="copyto">Click
</button>
a7qyws3x

a7qyws3x1#

您必须为<p>标签设置新颜色。这对样式优先级很重要。

var prelearnBtn = document.getElementById("copyto");
prelearnBtn.addEventListener("click", function() {
  setTimeout(function() {
    document.querySelector("#quotedes > p").style.color = "blue";
  }, 100);
});
p {
  color: green;
  font-size: 25px;
}
<code class="quotedes" id="quotedes">
    <p>Hello</p>
 </code>
<p>default text </p>
<button id="copyto">Click
</button>
jm81lzqq

jm81lzqq2#

问题中提到的代码工作正常。除了在这里,当你把颜色改为蓝色时,你是用代码片段id来改变它的。这应该是为段落做的。因此,我取了那个id的第一个孩子,并为那个元素分配了一个样式。

var prelearnBtn = document.getElementById("copyto");
prelearnBtn.addEventListener("click", function() {
  setTimeout(function() {
    let parentEle = document.getElementById("quotedes");
    parentEle.children[0].setAttribute('style',  "color:blue");
  }, 100);
});
p {
  color: green;
  font-size: 25px;
}
<code class="quotedes" id="quotedes">
    <p>Hello</p>
 </code>
<p>default text </p>
<button id="copyto">Click
</button>
hof1towb

hof1towb3#

var prelearnBtn = document.getElementById("copyto");
prelearnBtn.addEventListener("click", function() {
  setTimeout(function() {
    document.getElementById("quotedes").style.color = "blue";
  }, 100);
});
p {
  color: green;
  font-size: 25px;
}
<code class="quotedes" id="quotedes">
    <p>Hello</p>
 </code>
<p>default text </p>
<button id="copyto">Click
</button> 
#enter code here#
<body>
<script>
const btn = document.getElementById("copyto/");
const para = document.querySelector("p");
btn.addEventListener("click", function () {
para.quotedes = "colorRed";
});
</script>
<body>
vuktfyat

vuktfyat4#

var prelearnBtn = document.getElementById("copyto");
prelearnBtn.addEventListener("click", function() {
  setTimeout(function() {
    document.getElementById("quotedes").style.setProperty("--p-color", "blue");
  }, 100);
});
p {
  color: var(--p-color, green);
  font-size: 25px;
}
h2 {
  color: var(--p-color, green);
  font-size: 14;
}
<code class="quotedes" id="quotedes">
    <p>Hello</p>
    <h2>Hello2</h2>
 </code>
<p>default text </p>
<button id="copyto">Click
</button>

相关问题