我试图使用JavaScript与风格的文字段落来替换字符的JavaScript更换字符。如果我替换一个字符用一种风格,它工作正常,但是当我尝试更换3种不同风格的3个不同的字符段打印3次,每次只有1作风转变。我想让这三种款式在1款中生效。以下是我正在使用的代码。谢谢。使用各种<span>标签
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(){
var pText=document.getElementById("alteredText").innerHTML;
var eSpan=pText.replace(/e/g,"<span style='position:relative;color:red;top:.05em;'>e</span>");
var tSpan=pText.replace(/t/g,"<span style='position:relative;color:blue;top:-.05em;'>t</span>");
var sSpan=pText.replace(/s/g,"<span style='color:green;'>s</span>");
var n = eSpan.concat(tSpan,sSpan);
document.getElementById("alteredText").innerHTML=n;
}
</script>
</head>
<body onLoad="myFunction()">
<p id="alteredText">
The quick brown fox jumped over the lazy sleeping dog.
The slow shiny robot chased the quick brown fox.
The lazy sleeping dog awoke and barked at the slow shiny robot.
</p>
</body>
</html>
替代通常像这样的链接(例如:'pText.replace()代替()代替()')不过这不会工作,新增文本将匹配't'和's',所以你需要使用正则表达式更好,功能更多的替代品,检查被匹配什么字符,并适当地将其替换。 – zzzzBov