在文本框中设置文本格式

Format a text in the textbox

本文关键字:置文本 格式 文本      更新时间:2023-09-26

我试图将选定的文本格式化为文本框内的粗体,但没有发生。然而,它发生在span/div中。我的代码

<html> 
<head> 
<title>Untitled Document</title> 
<script type="text/javascript"> 
function FormatSelectedWord(txtBox,style) 
{ 
var selectedText = document.selection 
? document.selection.createRange().text 
: txtBox.value.substring(txtBox.selectionStart,txtBox.selectionEnd); 
if(selectedText!='') 
{ 
var newText='<'+style+'>'+selectedText+'</'+style+'>'; 
txtBox.value=txtBox.value.replace(selectedText,newText) 
spOutput.innerHTML=txtBox.value; 
} 
} 
</script> 
</head> 
<body> 

<input type="text" name="txtBox"> </input> 
<input type="button" value="Bold" onclick="FormatSelectedWord(txtBox,'b')"> 
<span id="spOutput"></span> 
</body> 
</html> 

是否可以在文本框中执行。如果有,那是怎么回事?

谢谢

不可以在文本框中设置文本样式。如果需要可编辑的格式化文本,可以设置div或span的contentEditable=true

与其重新发明轮子,不如看看实现TinyMCE或其他类似的东西——这很容易。这是一个非常常见的功能,它被称为"富文本编辑器",如果你想去谷歌搜索:)

试图自己添加这种功能是一个巨大的麻烦,你真的不想参与进来:)

这是我认为你想要的一个例子:http://jsfiddle.net/6gQJC/1/

,这是你问的:http://jsfiddle.net/6gQJC/

txtBox is undefined

所以这个:

<input type="text" name="txtBox"> </input>

必须是

<input type="text" id="txtBox" name="txtBox"> </input> 

function FormatSelectedWord(txtBox,style) 
{ 
     var textbox = document.getElementById('textBox');