HTML富文本编辑ZZ

这个原理实在是太简单了!对于支持富文本编辑的浏览器来说,其实就是设置 document 的 designMode 属性为 on 后,再通过执行 document.execCommand('commandName'[, UIFlag[, value]]) 即可。commandName 和 value 可以在 MSDN 上和MDC 上找到,它们就是我们创建各种格式的命令,比方说,我们要加粗字体,执行 document.execCommand('bold', false) 即可。很简单是吧?但是值得注意的是,通常是选中了文本后才执行命令,被选中的文本才被格式化。对于未选中的文本进行这个命令,各浏览器有不同的处理方式,比方 IE 可能是对位于光标中的标签内容进行格式化,而其它浏览器不做任何处理,这超出本文的内容,不细述。同时需要注意的是,UIFlag 这个参数设置为 true 表示 display any user interface triggered by the command (if any), 在我们今天的教程中都是 false, 而 value 也只在某些 commandName 中才有,具体参考以上刚给出的两个链接。

为了不影响当前 document, 通常的做法是在页面中嵌入一个 iframe 元素,然后对这个 iframe 内的 document(通过 iframe.contentWindow.document 获得)进行操作。

十分简单,是吧?下面我们来动手做一个。

<script language="javascript">
var editor;
editor = document.getElementById("HtmlEdit").contentWindow;

//只需键入以下设定,iframe立刻变成编辑器。
editor.document.designMode = 'On';
editor.document.contentEditable = true;

//但是IE与FireFox有点不同,为了兼容FireFox,所以必须创建一个新的document。
editor.document.open();
editor.document.writeln('<html><body></body></html>');
editor.document.close();

//字体特效 - 加粗方法一
function addBold()
{
editor.focus();
//所有字体特效只是使用execComman()就能完成。
editor.document.execCommand("Bold", false, null);
}
//字体特效 - 加粗方法二
function addBold()
{
editor.focus();
//获得选取的焦点
var sel = editor.document.selection.createRange();
insertHTML("<b>"+sel.text+"</b>");
}
function insertHTML(html)
{
if (editor.document.selection.type.toLowerCase() != "none")
{
editor.document.selection.clear() ;
}
editor.document.selection.createRange().pasteHTML(html) ;
}

</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值