我試圖使用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