用Javascript 编写 HTML在线编辑器

在线编辑器主要有3大类:1.直接用textarea 标签

优点:速度快,提交方便,可以用UBB标签来弥补不能所见所得

缺点:不直观,功能非常少

2.用 DIV或者TABLE的CONTENTEDITABLE 标签,属性来让一个区域可以编辑

优点:可以很直观,可以做各种效果

缺点:此标签在mozilla下不可用,只适合IE浏览器,且对js要求高

3.用iframe或者frame的中的document的document.designMode ="On" 来实现可编辑

优点:具有上面第二条的全部优点,并且还多浏览器比如FF等支持

缺点:对js要求高.

以前一直不知道好多网站上所说的在线编辑器是怎么回事,后来在文档里发现document 对象的一个方法。

document.execCommand(command, false, value);

才知道具体原理。

一、首先来看一个例子:

<DIV contenteditable="true" style="border:dashed blue 2px">Hello World!</DIV>

保存为html网页,打开看看,在DIV里出现了一个光标,这个DIV就变成可以编辑的了。

类似的,SPAN,FONT等都可以有 contenteditable="true" 这个属性。

再试试下面的:

<DIV contenteditable="true" style="border:dashed blue 2px">Hello World!

<IMG src="http://p.blog.csdn.net/images/p_blog_csdn_net/comstep/70786/o_logo.jpg" />

</DIV>

我们就可以拉伸图片了。

二、具体实现:

1、需要两个页面,blank.html editor.html

2、blank.html 作为 editor.html的一个内嵌Frame,作为编辑框。

<html>

<body topmargin="10" leftmargin="10" bgColor="#f6f6f6">

<div id="RTC" contenteditable = true></div>

</body>

</html>

3、editor.html 主要是一些Javascript,用来处理不同的命令。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE> New Document </TITLE>

<META NAME="Generator" CONTENT="EditPlus">

<META NAME="Author" CONTENT="">

<META NAME="Keywords" CONTENT="">

<META NAME="Description" CONTENT="">

<SCRIPT LANGUAGE="JavaScript">

<!--

var contentHTML;

function exeCommand(command, value)

{

document.execCommand(command, false, value);

}

// 加粗

function Black()

{

var obj = frames[‘ifRTC‘].RTC;

obj.focus();

exeCommand(‘Bold‘, ‘‘);

}

// 斜体

function Italic()

{

var obj = frames[‘ifRTC‘].RTC;

obj.focus();

exeCommand(‘Italic‘, ‘‘);

}

// 下划线

function UnderLine()

{

var obj = frames[‘ifRTC‘].RTC;

obj.focus();

exeCommand(‘Underline‘, ‘‘);

}

// 向里缩进

function Indent()

{

var obj = frames[‘ifRTC‘].RTC;

obj.focus();

exeCommand(‘Indent‘, ‘‘);

}

// 向外缩进

function Outdent()

{

var obj = frames[‘ifRTC‘].RTC;

obj.focus();

exeCommand(‘Outdent‘, ‘‘);

}

// 无序列表

function UnorderList()

{

var obj = frames[‘ifRTC‘].RTC;

obj.focus();

exeCommand(‘InsertUnorderedList‘, ‘‘);

}

// 有序列表

function OrderList()

{

var obj = frames[‘ifRTC‘].RTC;

obj.focus();

exeCommand(‘InsertOrderedList‘, ‘‘);

}

// 插入图片

function Image()

{

var obj = frames[‘ifRTC‘].RTC;

obj.focus();

ImagePath = window.prompt(‘请输入图片路径:‘, ‘‘);

exeCommand(‘InsertImage‘, ImagePath);

}

// 预览效果

function Preview()

{

var htmlContent = frames[‘ifRTC‘].RTC.innerHTML;

var open = window.open(‘‘);

open.document.write(htmlContent);

}

// 查看编辑框里的HTML源代码

function Source()

{

var htmlContent = frames[‘ifRTC‘].RTC.innerHTML;

if (document.all.iframeDiv.style.display == ‘block‘)

{

document.all.iframeDiv.style.display = ‘none‘;

document.all.htmlText.value = htmlContent;

document.all.textDiv.style.display = ‘block‘;

document.all.htmlText.focus();

document.all.Source.value=‘HTML‘;

}

else

{

document.all.iframeDiv.style.display = ‘block‘;

document.all.textDiv.style.display = ‘none‘;

frames[‘ifRTC‘].RTC.innerHTML = document.all.htmlText.value;

frames[‘ifRTC‘].RTC.focus();

document.all.Source.value=‘ 源代码 ‘;

}

}

// 增加编辑框的高度

function Add()

{

document.all.ifRTC.height = document.all.ifRTC.height*1 + 50;

}

//-->

</SCRIPT>

</HEAD>

<BODY>

<TABLE width="400"border="0">

<TR>

<TD><input type="button" value="B" name="Black"  /></TD>

<TD><input type="button" value="I" name="Italic"  /></TD>

<TD><input type="button" value="U" name="UnderLine"  /></TD>

<TD><input type="button" value="UL" name="UnorderList"  /></TD>

<TD><input type="button" value="OL" name="OrderList"  /></TD>

<TD><input type="button" value="左" name="Outdent"  /></TD>

<TD><input type="button" value="右" name="Indent"  /></TD>

<TD><input type="button" value="图" name="Image"  /></TD>

</TR>

</TABLE>

<div id="iframeDiv" style="display:block">

<iframe id="ifRTC" width="400" height="200" border="1" src="blank.html" ></iframe>

</div>

<div id="textDiv" style="display:none">

<textarea id="htmlText" cols="50" rows="10"></textarea>

</div>

<br>

<input type="button" value=" + " name="Add"  />&nbsp;&nbsp;

<input type="button" value=" 预 览 " name="Preview"  />&nbsp;&nbsp;

<input type="button" value=" 源代码 " name="Source"  />

</BODY>

</HTML>

三、后记:

这里写的只是一个简单的编辑器,其实重要的就是:

contenteditable="true"

document.execCommand(command, false, value);

关于 document 的一些方法,可以查看MS的文档。

execCommand 的一些命令也可以在文档里找到,下面列出一些:

execCommand(command, false, value); 中的 command 可以是以下这些:

BackColorSets or retrieves the background color of the current selection.

BoldToggles the current selection between bold and nonbold.

ClearAutocompleteForFormsClears saved forms data.

CopyCopies the current selection to the clipboard.

CreateBookmarkRetrieves the name of a bookmark anchor or creates a bookmark anchor for the current selection or insertion point.

CreateLinkRetrieves the URL of a hyperlink or creates a hyperlink on the current selection.

CutCopies the current selection to the clipboard and then deletes it.

DeleteDeletes the current selection.

FontNameSets or retrieves the font for the current selection.

FontSizeSets or retrieves the font size for the current selection.

ForeColorSets or retrieves the foreground (text) color of the current selection.

FormatBlockSets or retrieves the current block format tag.

IndentIncreases the indent of the selected text by one indentation increment.

InsertButtonOverwrites a button control on the current selection.

InsertFieldsetOverwrites a box on the current selection.

InsertHorizontalRuleOverwrites a horizontal line on the current selection.

InsertIFrameOverwrites an inline frame on the current selection.

InsertImageOverwrites an image on the current selection.

InsertInputButtonOverwrites a button control on the current selection.

InsertInputCheckboxOverwrites a check box control on the current selection.

InsertInputFileUploadOverwrites a file upload control on the current selection.

InsertInputHiddenInserts a hidden control on the current selection.

InsertInputImageOverwrites an image control on the current selection.

InsertInputPasswordOverwrites a password control on the current selection.

InsertInputRadioOverwrites a radio control on the current selection.

InsertInputResetOverwrites a reset control on the current selection.

InsertInputSubmitOverwrites a submit control on the current selection.

InsertInputTextOverwrites a text control on the current selection.

InsertMarqueeOverwrites an empty marquee on the current selection.

InsertOrderedListToggles the current selection between an ordered list and a normal format block.

InsertParagraphOverwrites a line break on the current selection.

InsertSelectDropdownOverwrites a drop-down selection control on the current selection.

InsertSelectListboxOverwrites a list box selection control on the current selection.

InsertTextAreaOverwrites a multiline text input control on the current selection.

InsertUnorderedListToggles the current selection between an ordered list and a normal format block.

ItalicToggles the current selection between italic and nonitalic.

JustifyCenterCenters the format block in which the current selection is located.

JustifyLeftLeft-justifies the format block in which the current selection is located.

JustifyRightRight-justifies the format block in which the current selection is located.

OutdentDecreases by one increment the indentation of the format block in which the current selection is located.

OverWriteToggles the text-entry mode between insert and overwrite.

PasteOverwrites the contents of the clipboard on the current selection.

RefreshRefreshes the current document.

RemoveFormatRemoves the formatting tags from the current selection.

SelectAllSelects the entire document.

SaveAsSaves the current Web page to a file.

UnBookmarkRemoves any bookmark from the current selection.

UnderlineToggles the current selection between underlined and not underlined.

UnlinkRemoves any hyperlink from the current selection.

UnselectClears the current selection.

过滤html在线编辑器产生有危害代码

2008-04-03 14:03

部分强大的在线编辑器,已经包含了代码整理,过滤功能,但js处理的能被很轻易的饶过,服务端必须要再次过滤一次,这几天花了点时间,写了部分,希望对大家有点用处,本人能力有限,还请有能力的朋友补全它。

/*不需要过滤的数组*/

$htm_on=array(

"<acronym","acronym>",

"<baseFont","baseFont>",

"<button","button>",

"<caption","caption>",

"<clientInformation","clientInformation>",

"<font","font>",

"<implementation","implementation>",

"<button","button>",

"<location","location>",

"<option","option>",

"<selection","selection>",

"<strong","strong>",

"font");

$htm_on_uper=array(

"<ACRONYM","ACRONYM>",

"<BASEFONT","BASEFONT>",

"<BUTTON","BUTTON>",

"<CAPTION","CAPTION>",

"<CLIENTINFORMATION","CLIENTINFORMATION>",

"<FONT","FONT>",

"<IMPLEMENTATION","IMPLEMENTATION>",

"<BUTTON","BUTTON>",

"<LOCATION","LOCATION>",

"<OPTION","OPTION>",

"<SELECTION","SELECTION>",

"<STRONG","STRONG>",

"FONT");

/*字符格式*/

$str=strtolower($str);

$str=preg_replace("/\s+/", " ", $str);//过滤回车

$str=preg_replace("/ +/", " ", $str);//过滤多个空格

/*过滤/替换几种形式的js*/

$str=preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si","",$str);//删除<script>。。。</script>格式,

//$str=preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si","&lt;\\1&gt;\\2&lt;\\3&gt;",$str);//替换为可以显示的,

$str=preg_replace("/<(script.*?)>/si","",$str);//删除<script>未封闭

//$str=preg_replace("/<(script.*?)>/si","&lt;\\1&gt;",$str);//替换未封闭

/*删除/替换表单*/

$str=preg_replace("/<(\/?form.*?)>/si","",$str);//删除表单

//$str=preg_replace("/<(\/?form.*?)>/si","&lt;\\1&gt;",$str);//替换表单

$str=preg_replace("/<(i?frame.*?)>(.*?)<(\/i?frame.*?)>/si","",$str);//删除框架

//$str=preg_replace("/<(i?frame.*?)>(.*?)<(\/i?frame.*?)>/si","&lt;\\1&gt;\\2&lt;\\3&gt;",$str);//替换框架

/*过滤on事件*/

$str=preg_replace("/href=(.+?)([\"|\‘| |>])/ie","‘href=‘.strtoupper(‘\\1‘).‘\\2‘",$str);//把href=涉及到的on转换为大写。

$str=str_replace($htm_on,$htm_on_uper,$str);//把<font,font>换为大写,dhtml标签字符,正则判断太烦琐,采用转换办法。

$str=preg_replace("/(on[^ \.<>]+?)([ |>])/s","\\2",$str);//取掉on事件

/*过滤超级连接的js*/

$str=preg_replace("/(href|src|background|url|dynsrc|expression|codebase)[=:\(]([ \"\‘]*?\w+\..*?|javascript|vbscript:[^>]*?)(\)?)([ >\/])/si","\\1=‘#‘ \\3\\4",$str);//取掉href=javascript:

//返回小写字符

$str=strtolower($str);

$str=str_replace("&","&",$str);

时间: 2024-08-24 12:57:26

用Javascript 编写 HTML在线编辑器的相关文章

Html、CSS、JavaScript 实时效果在线编辑器 - 学习的好工具,算不算?!

关于 二维码 与 NFC 之间的出身贫贱说 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS.Android.Html5.Arduino.pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作. http://jsfiddle.net/vnkuZ/ 总共四个工作区:左上是 Html 界面组件:左下

关于OSChina相关的在线编辑器简介

UEditor 是什么?官网 ??UEditor是由百度WEB前端研发部开发的所见即所得的开源富文本编辑器,具有轻量.可定制.用户体验优秀等特点.开源基于BSD协议,所有源代码在协议允许范围内可自由修改和使用.百度UEditor的推出,可以帮助不少网站开发者在开发富文本编辑器所遇到的难题,节约开发者因开发富文本编辑器所需要的大量时间,有效降低了企业的开发成本. 主要特点 [email protected]体积小巧,性能优良,使用简单 [email protected]分层架构,方便定制与扩展 [

Angularjs在线编辑器

1.TextAngular: https://github.com/fraywing/textAngular textAngular是一个强大的Text-Editor/Wysiwyg 编辑器,用于Angular.js应用中.安装使用方便,可以创建多个编辑器实例,双向绑定HTML内容,可以查看编辑内容的变化.不足之处是不支持上传文件到服务器,只能进行简单的文字编辑,可用于网站的用户评论模块 2.angular.xheditor: https://github.com/cipchk/angular.

PHP.25-TP框架商城应用实例-后台1-添加商品功能、钩子函数、在线编辑器、过滤XSS、上传图片并生成缩略图

添加商品功能 1.创建商品控制器[C] /www.test.com/shop/Admin/Controller/GoodsController.class.php <?php namespace Admin\Controller; use Think\Controller; //后台添加商品功能控制器 class GoodsController extends Controller { //显示和处理表单 public function add() { //判断用户是否提交了表单(如果提交了,就

在线编辑器Ckeditor (1) - php (30)

在线编辑器 在线编辑器也称之为所见即所得编辑器,是一种常见的html源码编辑器. 所见即所得:用户在输入的时候,不论是格式和是样式都能被系统原封不动的保存,最后在查看的时候,可以按照用户输入的原来的结构进行输出. 在线编辑器分类 市面上比较常见的在线编辑器有很多,FCKeditor(在线编辑器+Ajax浏览器端服务器文件管理器,免费的),Ckeditor(Content and Knowledge,在线编辑器与服务器端文件管理器分离,在线编辑器免费,服务器端文件管理器收费(CKfinder)),

将kindeditor在线编辑器制作成smarty插件

在web开发中,在线编辑器是经常要用到的功能模块,虽说配置在线编辑器没有多大难度,但是每一次编写重复的代码,总是让人感觉不爽. 本篇,就来讲解一下,如何将kindeditor制作成smarty的一个自定义函数. 为什么要制作成自定义函数呢?当然是为了避免写很多重复的代码. {html_kindeditor name="kindcontent"} 假如在模板中调用一个smarty标签,就能生成一个文本编辑器(如上),那开发起来会不会感觉很过瘾呢? 好了,说下流程(本文以集成了smarty

百度在线编辑器 代码高亮

原文:http://www.upwqy.com/details/28.html 使用百度在线编辑器 ,添加的内容,在前台显示的时候 代码部分只是重点突出了.但是没有代码高亮 想要使其代码高亮. 首先加载 文件 这里是在TP5中 {js href="/static/ue/third-party/SyntaxHighlighter/shCore.js"} {css href="/static/ue/third-party/SyntaxHighlighter/shCoreDefau

CKedit在线编辑器

在线编辑器???? ????在实现所见即得的编辑效果. FCK????????????是开发者的名字的缩写 CKEditor????????功能很完善的,具有,在线编辑与图片上传JS插件 UEdit????????????百度自己开发的一款在线编辑器 ? CKeditor安装 http://resource.ckeditor.com/ basic package????????基本安装包????????只包含了基本的功能 standard package????标准安装包????????包含更多

【教程】HTML5+JavaScript编写flappy bird

     作者: 风小锐      新浪微博ID:永远de风小锐      QQ:547953539      转载请注明出处 PS:新修复了两个bug,已下载代码的同学请查看一下 大学立即要毕业了.未来的公司为我们制定了在校学习计划.希望我们能在毕业之前掌握一些技术,当中有一项就是使用HTML5+JavaScript编写flappy bird这个小游戏. 相信大家和我一样,对这个小游戏还是非常熟悉的,控制小鸟跳过高矮不一的水管,并记录下每局得到的分数,对于亲手编写这个小游戏非常感兴趣,立即開始