-1
我想编码使用html和javascript的文本编辑器。我找到了下面的提琴,我们可以在一个文本区域中输入文本,点击预览按钮后,可以在其下方的区域中看到预览。编写在线文本编辑器
我想摆脱预览区域,并在输入文本的同一文本区域中显示文本粗体。这怎么能实现。
下面是代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#my_textarea{
width:300px;
height:150px;
border:thin solid #000;
color:#000;
padding:10px;
min-height:150px;
min-width:300px;
max-height:150px;
max-width:300px;
}
#preview{
width:300px;
height:150px;
border:thin solid #000;
color:#000;
padding:10px;
min-height:150px;
min-width:300px;
max-height:150px;
max-width:300px;
}
</style>
<script type="text/javascript">
function formatText(tag) {
var myTextArea = document.getElementById('my_textarea');
var myTextAreaValue = myTextArea.value;
var selected_txt = myTextAreaValue.substring(myTextArea.selectionStart, myTextArea.selectionEnd);
var before_txt = myTextAreaValue.substring(0, myTextArea.selectionStart);
var after_txt = myTextAreaValue.substring(myTextArea.selectionEnd, myTextAreaValue.length);
myTextArea.value = before_txt + '<' + tag + '>' + selected_txt + '</' + tag + '>' + after_txt;
}
function preview() {
var textbox , view ;
textbox = document.getElementById('my_textarea');
view = document.getElementById("preview");
view.innerHTML = textbox.value
}
function onload(){
var textarea = document.getElementById("my_textarea");
textarea.onkeypress = function(e){
if(e.which === 13)
{
this.value += "<br>";
}
}
}
</script>
</head>
<body onLoad="onload();">
<input type="button" value="bold" onClick="formatText ('b');" />
<input type="button" value="italic" onClick="formatText ('i');" />
<input type="button" value="underline" onClick="formatText ('u');" /><br><br>
<textarea name="my_textarea" id="my_textarea"></textarea><br><br>
<div id="preview"></div><br>
<button id="btn" onClick="preview();">Preview</button>
</body>
</html>
JS小提琴:http://jsfiddle.net/yZ6Va/
你不能,'textarea'不能有HTML。您必须使用例如可编辑的div或pre元素而不是textarea。 – Teemu