[英]Can i change the paragraph text and at the same time keep the CSS(the coloring) for the span elements inside the paragraph?
这是我正在尝试更改的 HTML,并且我正在尝试为包装在标签中的单词保留颜色(CSS) - 纸和岩石。 基本上我想更改和中的文本
并保留 2 个标签的 CSS(着色)。
HTML:
<div class="message">
<p><span id="result-user">Paper</span> beats <span id="result-comp">Rock</span>!You win!</p>
</div>
CSS:
#result-user{
color: rgb(246, 189, 76);
}
#result-comp{
color: rgb(246, 189, 76);
}
JavaScript:
let resultUserMessage_span = document.getElementById('result-user');
let resultCompMessage_span = document.getElementById('result-comp');
let resultMessage_p = document.querySelector('.message > p');
userChoice = "Rock";
compChoice = "Paper";
resultMessage_p.innerHTML = `${userChoice} loses to ${compChoice}!You lose!`;
更改innerHTML
时插入具有正确 ID 的跨度
resultMessage_p.innerHTML = `<span id="result-user">${userChoice}</span> loses to <span id="result-comp">${compChoice}</span>! You lose!`;
在您的 function 中,尝试
document.getElementById("p1").innerHTML = "<span id="result-user">${userChoice}</span> beats <span id="result-comp">${compChoice}</span>!You lose!";
一个简单的解决方案是用 span 元素包装你的代码
resultMessage_p.innerHTML = `<span id="result-user">${userChoice}</span> loses to <span id="result-comp">${compChoice}</span> !You lose!`
更好的方法是通过向答案的每个部分添加跨度并根据“游戏”的状态更改 innerHTML 来模块化地处理您的答案
<p>
<span id="result-user">Rock</span>
<span id="result-status"> loses to </span>
<span id="result-comp">Paper</span>!
<span id="final-result"> You lose!</span>
</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.