"rich" textarea editor.前段时间有个霓虹灯的小项目。后台用asp.net给硬件传接口(具体怎样就不清楚了),前台网页让做个可即时变色的textarea editor,把内容传给后台就行了。其实如果不要求即时变色的话,自定义个命名规则就行了。试了document.selection,可惜只支持IE而且bug不少(比如不能隔行操作)。后来搜到了一些开源的editor,用纯js写的小框架。
自己也用iframe写了个简单的,一般功能是没问题了:
程序目录结构
img
***.gif
js
common.js
iframe.html
test.html
test.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
2 "http://www.w3.org/TR/html4/loose.dtd">
3 <html>
4 <head>
5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
6 <style type="text/css">
7 img{cursor:pointer;}
8 .class1{
9 border:solid 1px;
10 width:600px;
11 height:400px;
12 }
13 </style>
14 <script type="text/javascript" src="js/common.js"></script>
15 <title>iframe editor</title>
16 </head>
17 <body onload="init()">
18 <form id="form1">
19
20 <div style="width:600px">
21 <div align=right style="float:right;">
22 <img src="img/1.gif" onclick="chgFont()" title="Change Font!" />
23 <img src="img/2.gif" onclick="addIMG()" title="Add Image!" />
24
25 </div>
26 </div>
27
28 <iframe src="iframe.html" id="editor" class="class1"></iframe>
29
30 <div style="width:600px" align=right>
31 <input type="button" id="button1" value="Get Editor Value" onclick="getDocValue()" />
32 </div>
33
34 </form>
35 </body>
36 </html>
iframe.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
2 "http://www.w3.org/TR/html4/loose.dtd">
3 <html>
4 <head>
5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
6 </head>
7 <body>Hello World! 啊啊</body>
8 </html>
common.js
1 function $(tagid){
2 return document.getElementById(tagid);
3 }
4
5 function getDocValue(){
6 alert($("editor").contentWindow.document.body.innerHTML);
7 }
8
9 function init(){
10 var win = $("editor").contentWindow;
11 win.document.designMode= "on";
12 win.document.contentEditable = true;
13 win.focus();
14 }
15
16 function chgFont() {
17 var win=$("editor").contentWindow;
18 win.document.execCommand("ForeColor",false,"red");
19 win.document.execCommand("FontSize",false,"10");
20 win.focus();
21 }
22
23 function addIMG() {
24 var win=$("editor").contentWindow;
25 win.document.execCommand("InsertImage",false,"img/a.gif");
26 win.focus();
27 }