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