如何在jQuery中更改文本的颜色?

时间:2019-03-05 15:22:17

标签: javascript jquery html

游戏结束后,我使用jQuery更改了h1标头,并且有以下代码行:

$('h1').text(winningPlayer+" has won!").css("fontSize", "55px");

问题是,如何仅为文本的winningPlayer部分设置不同的颜色?

1 个答案:

答案 0 :(得分:4)

winningPlayer中将<span>包裹起来,然后将.text()更改为.html()。下面是演示

let winningPlayer = "John"
$('h1').html(`<span style="color:blue">${winningPlayer}</span> has won!`).css("fontSize", "55px");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1></h1>