Javascript 格式化文本框中的文本

Javascript 格式化文本框中的文本,javascript,Javascript,我正在尝试将文本框中的选定文本格式化为粗体,但没有成功。然而,它在span/div中出现。我的代码 <html> <head> <title>Untitled Document</title> <script type="text/javascript"> function FormatSelectedWord(txtBox,style) { var selectedText = document.selection ?

我正在尝试将文本框中的选定文本格式化为粗体,但没有成功。然而,它在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> 

无标题文件
函数格式SelectedWord(txtBox,样式)
{ 
var selectedText=document.selection
?document.selection.createRange().text
:txtBox.value.substring(txtBox.selectionStart、txtBox.selectionEnd);
如果(已选择文本!='')
{ 
var newText=''+selectedText+'';
txtBox.value=txtBox.value.replace(selectedText,newText)
spOutput.innerHTML=txtBox.value;
} 
} 
是否可以在文本框中执行此操作。如果是,怎么做


谢谢

与其重新发明轮子,不如考虑实施或其他类似的方法来实现这一点——这非常简单。这是一个非常受欢迎的功能,它被称为“富文本编辑器”,如果你想去谷歌搜索:)


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

下面是一个我认为你想要的例子:

以下是你的问题:

因此:

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

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

我怎么会不知道这个?!
<input type="text" name="txtBox"> </input>
<input type="text" id="txtBox" name="txtBox"> </input> 
function FormatSelectedWord(txtBox,style) 
{ 
     var textbox = document.getElementById('textBox');