2011-09-10 49 views
3

我试图在文本框中将所选文本格式化为粗体但不会发生。但是,这是一个跨度/格。我的代码在文本框中设置文本的格式

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

是否可以在insde文本框中执行此操作。如果是这样如何?

感谢

回答

3

不,这是不可能的样式在文本框中的文本。如果您需要可编辑的格式化文本,则可以使div或span contentEditable = true。

+0

我怎么从来不知道这个? – Marcel

0

而不是重新发明轮子,你最好还是考虑一下实施TinyMCE或者,这是否有些其他类似的东西 - 它很容易。这是非常常见的功能追求,它被称为“富文本编辑器”,如果你想要谷歌搜索:)

试图自己添加这种功能是巨大的蠕虫病毒,你真的不想涉足:)

0

这里是什么,我想你一个例子想: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');