如果CSS样式已经定义,请使用JS更改<p>下的文本颜色样式

问题描述 投票:0回答:4

p标签的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>

javascript html css colors
4个回答
3
投票

您必须为

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


2
投票

问题中提到的代码工作正常。 除了在这种情况下,当您将颜色更改为蓝色时,您将使用代码片段 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>


1
投票

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>


1
投票

    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>

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