2

我正在尝试使用 javascript 用样式字符替换段落中的字符。如果我用一种样式替换一个字符,效果很好,但是当我尝试用 3 种不同的样式替换 3 个不同的字符时,该段落会打印 3 次,每次只有 1 次样式更改。我希望 3 种样式在 1 段中生效。下面是我正在使用的代码。谢谢你。

<!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>
4

3 回答 3

2
var pText=document.getElementById("alteredText").innerHTML;  
var t = pText.replace(/e/g,"@e@");     
t = t.replace(/t/g,"@t@");        
t = t.replace(/s/g,"@s@");        
t = t.replace(/@e@/g,"<span style='position:relative;color:red;top:.05em;'>e</span>");  
t = t.replace(/@t@/g,"<span style='position:relative;color:blue;top:-.05em;'>t</span>");  
t = t.replace(/@s@/g,"<span style='color:green;'>s</span>");  
document.getElementById("alteredText").innerHTML=t;
于 2012-09-21T18:54:30.583 回答
0

尝试这个:

var first = pText.replace(/e/g,"<span style='position:relative;color:red;top:.05em;'>e</span>"); 
var second = first.replace(/t/g,"<span style='position:relative;color:blue;top:-.05em;'>t</span>"); 
var final = second.replace(/s/g,"<span style='color:green;'>s</span>"); 
document.getElementById("alteredText").innerHTML=final;

看看我做了什么?您正在创建三个字符串,每个字符串都有一个替换。在这里,我正在对已经包含第一个的字符串进行第二次替换。最后一次替换后,我把它放在了元素中。

于 2012-09-21T18:50:27.833 回答
0

一种快速而肮脏的解决方案:

function myFunction (){
    var pText=document.getElementById("alteredText").innerHTML;
    var eSpan=pText.replace(/e/g,"<SPAN STYLE='POSITION:RELATIVE;COLOR:RED;TOP:.05EM;'>e</SPAN>");  // CAPS are needed so no match is found in the next replace
    var tSpan=eSpan.replace(/t/g,"<SPAN STYLE='POSITION:RELATIVE;COLOR:BLUE;TOP:-.05EM;'>t</SPAN>");
    var sSpan=tSpan.replace(/s/g,"<SPAN STYLE='COLOR:GREEN;'>s</SPAN>");
    // var n = eSpan.concat(tSpan,sSpan);   //<-- this creates the three copies of the paragraph. you don't need this.
    document.getElementById("alteredText").innerHTML=sSpan;
}

http://jsfiddle.net/DUN4C/

于 2012-09-21T18:58:27.967 回答