如何在JavaScript中鼠标悬停时更改字母的颜色
问题描述:
这是我的代码:
$(document).ready(function(){
var letters = $('p').text();
for(var letter of letters) {
$(letter).wrap("<span class='x'></span>");
}
})
.x:hover {
color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p>Hello World!</p>
例如,当我将鼠标悬停在 r
时>, r
的颜色为 orange
,没有其他字母。
For example, I want when hovering on r
, the color of r
to be orange
and no other letters.
答
您可以先使用< span class ='x创建新的HTML内容>
为< p>
中的每个字符添加,然后替换< p> $ c的HTML $ c>使用该HTML。现在,当您将鼠标悬停在每个字符上时,该字符的颜色将变为
orange
You can first create a new HTML content using <span class='x'>
for each character in <p>
and then replace the HTML of <p>
with that HTML. Now, when you hover over each character then the color of that character changes to orange
$(document).ready(function(){
var letters = $('p').text();
var nHTML = '';
for(var letter of letters) {
nHTML+="<span class='x'>"+letter+"</span>";
}
$('p').html(nHTML);
})
.x:hover {
color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p>Hello World!</p>