【发布时间】:2013-11-17 10:06:49
【问题描述】:
我正在使用 textarea 作为编辑器制作一个简单的富文本编辑器,我只需将 <tag><tag/> 粘贴为粗体、斜体和下划线在 textarea 中一切正常,问题是我无法理解如何使用插入有序列表和无序列表这个脚本。
下面是我的代码。
<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>
【问题讨论】:
-
为什么不直接使用
contenteditable? -
contenteditable中所有浏览器的enterkey的行为是改变IE产生p标签,chrome产生div标签和firefox产生br标签。
标签: javascript html