欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

学习js在线html(富文本,所见即所得)编辑器_基础知识

程序员文章站 2022-05-06 20:23:06
...
你要的是所见即所得HTML编辑器,简单来说需要几个基本步骤:

1,需要一个可以编辑同时又可显效果的编辑框。textarea不行,它只能用来输入纯文本,不能显示颜色、斜体之类的文字样式,就像记事本。
你可以使用iframe来实现,修改iframe的designMode属性使其可以被编辑。
复制代码 代码如下:




这样你就可以在这个iframe区域里写字了。

2,选中要添加样式的文字。通常我们用WORD编辑一段文字的样式时,一般是先打字,再编辑样式。所以你需要一个选中要处理文本的方法。JS的selection.createRange()可以选中文本,返回一个对象,你可以通过访问该对象的text属性得到被选中的文本。
复制代码 代码如下:





3,改变被选中文本的样式。selection.createRange()选中文本,返回一个对象,该对象有一个方法execCommand(),可以用来改变被选中文本的样式。
复制代码 代码如下:





execCommand()的常用用法
字体--宋体、黑体、楷体等
execCommand("fontname","",字体)
字号--字号大小
execCommand("fontsize","",字号)
加重
execCommand("Bold")
斜体
execCommand("Italic")
下划线
execCommand("Underline")
删除线
execCommand("StrikeThrough")
居左
execCommand("JustifyLeft")
居右
execCommand("JustifyRight")
居中
execCommand("JustifyCenter")
剪切
execCommand("Cut")
拷贝
execCommand("Copy")
粘贴
execCommand("Paste")
取消操作--IE5.0以后可以无限取消
execCommand("Undo")
重复操作
execCommand("Redo")

把上面的每个用法用按钮来实现,你就已经完成了一个简单的可视文本编辑器。
document.execCommand()用法说明
复制代码 代码如下:

Position 允许通过拖曳移动绝对定位的对象。
AbsolutePosition 设定元素的 position 属性为“absolute”(绝对)。
BackColor 设置或获取当前选中区的背景颜色。
BlockDirLTR 目前尚未支持。
BlockDirRTL 目前尚未支持。
Bold 切换当前选中区的粗体显示与否。
BrowseMode 目前尚未支持。
Copy 将当前选中区复制到剪贴板。
CreateBookmark 创建一个书签锚或获取当前选中区或插入点的书签锚的名称。
CreateLink 在当前选中区上插入超级链接,或显示一个对话框允许用户指定要为当前选中区插入的超级链接的 URL。
Cut 将当前选中区复制到剪贴板并删除之。
Delete 删除当前选中区。
DirLTR 目前尚未支持。
DirRTL 目前尚未支持。
EditMode 目前尚未支持。
FontName 设置或获取当前选中区的字体。
FontSize 设置或获取当前选中区的字体大小。
ForeColor 设置或获取当前选中区的前景(文本)颜色。
FormatBlock 设置当前块格式化标签。
Indent 增加选中文本的缩进。
InlineDirLTR 目前尚未支持。
InlineDirRTL 目前尚未支持。
InsertButton 用按钮控件覆盖当前选中区。
InsertFieldset 用方框覆盖当前选中区。
InsertHorizontalRule 用水平线覆盖当前选中区。
InsertIFrame 用内嵌框架覆盖当前选中区。
InsertImage 用图像覆盖当前选中区。
InsertInputButton 用按钮控件覆盖当前选中区。
InsertInputCheckbox 用复选框控件覆盖当前选中区。
InsertInputFileUpload 用文件上载控件覆盖当前选中区。
InsertInputHidden 插入隐藏控件覆盖当前选中区。
InsertInputImage 用图像控件覆盖当前选中区。
InsertInputPassword 用密码控件覆盖当前选中区。
InsertInputRadio 用单选钮控件覆盖当前选中区。
InsertInputReset 用重置控件覆盖当前选中区。
InsertInputSubmit 用提交控件覆盖当前选中区。
InsertInputText 用文本控件覆盖当前选中区。
InsertMarquee 用空字幕覆盖当前选中区。
InsertOrderedList 切换当前选中区是编号列表还是常规格式化块。
InsertParagraph 用换行覆盖当前选中区。
InsertSelectDropdown 用下拉框控件覆盖当前选中区。
InsertSelectListbox 用列表框控件覆盖当前选中区。
InsertTextArea 用多行文本输入控件覆盖当前选中区。
InsertUnorderedList 切换当前选中区是项目符号列表还是常规格式化块。
Italic 切换当前选中区斜体显示与否。
JustifyCenter 将当前选中区在所在格式化块置中。
JustifyFull 目前尚未支持。
JustifyLeft 将当前选中区所在格式化块左对齐。
JustifyNone 目前尚未支持。
JustifyRight 将当前选中区所在格式化块右对齐。
LiveResize 迫使 MSHTML 编辑器在缩放或移动过程中持续更新元素外观,而不是只在移动或缩放完成后更新。
MultipleSelection 允许当用户按住 Shift 或 Ctrl 键时一次选中多于一个站点可选元素。
Open 打开。
Outdent 减少选中区所在格式化块的缩进。
OverWrite 切换文本状态的插入和覆盖。
Paste 用剪贴板内容覆盖当前选中区。
PlayImage 目前尚未支持。
Print 打开打印对话框以便用户可以打印当前页。
Redo 重做。
Refresh 刷新当前文档。
RemoveFormat 从当前选中区中删除格式化标签。
RemoveParaFormat 目前尚未支持。
SaveAs 将当前 Web 页面保存为文件。
SelectAll 选中整个文档。
SizeToControl 目前尚未支持。
SizeToControlHeight 目前尚未支持。
SizeToControlWidth 目前尚未支持。
Stop 停止。
StopImage 目前尚未支持。
StrikeThrough 目前尚未支持。
Subscript 目前尚未支持。
Superscript 目前尚未支持。
UnBookmark 从当前选中区中删除全部书签。
Underline 切换当前选中区的下划线显示与否。
Undo 撤消。
Unlink 从当前选中区中删除全部超级链接。
Unselect 清除当前选中区的选中状态。

一个简单的开源编辑器
复制代码 代码如下:





Editor





": "";
this.ed.write("" + div + "");
this.ed.close();
this.ed.contentEditable = true;
this.ed.designMode = "on"; //设置编辑区为可编辑
for (var i = 0, l = data.length; i var o = create("span", this.toolbar);
Attr(o, {
title: data[i].title,
active: false,
unselectable: "on"
});
o.className = "tag " + data[i].Class;
addListener(o, "mouseover", Bind(this, this.Changebgcolor, o, data[i].hover));
addListener(o, "mouseout", Bind(this, this.Changebgcolor, o, data[i].Class));
addListener(o, "click", Bind(this, this[data[i].action], o, data[i].args));
}
//////////////////////////生成工具栏
addListener(this.iframe.contentWindow, "focus", Bind(this,
function() {
this.isfocus = true;
}));
addListener(this.iframe.contentWindow, "blur", Bind(this,
function() {
this.isfocus = false;
}));
addListener(this.ed, 'mousedown', Bind(this, this.Show));
addListener(this.ed, 'mouseup', Bind(this, this.Show));
//////////////////////////这2个事件是来判断光标所在位置是否别编辑
addListener(this.original, 'click', Bind(this, this.Showoriginal, this.original)); //显示源代码
},
Changebgcolor: function(o, name, p) {
if (o.active) return;
o.className = "tag " + name;
},
Show: function() {
var spans = $$(this.toolbar, "span"),
Is;
var elm = [[spans[0], "Bold", "tag span0_active", "tag span0"], [spans[1], "Italic", "tag span1_active", "tag span1"], [spans[2], "Underline", "tag span2_active", "tag span2"], [spans[12], "InsertUnorderedList", "tag span3_active", "tag span12"], [spans[13], "InsertOrderedList", "tag span4_active", "tag span13"]];
for (var i = 0, l = elm.length; i Is = this.ed.queryCommandState(elm[i][1]);
elm[i][0].className = Is ? elm[i][2] : elm[i][3];
elm[i][0].active = Is;
}
},
Showoriginal: function(o) {
if (!this.toolbarlayer) {
this.toolbarlayer = create("div", document.body);
this.toolbarlayer.className = "toolbarlayer";
var pos = Getpos(this.toolbar);
Css(this.toolbarlayer, {
width: this.option.width + "px",
left: pos.x + "px",
top: pos.y + "px"
});
}
if (o.checked) {
this.iframe.style.display = "none";
this.textarea.style.display = "block";
this.toolbarlayer.style.display = "block";
this.textarea.value = this.ed.body.innerHTML;
}
else {
this.iframe.style.display = "block";
this.textarea.style.display = "none";
this.toolbarlayer.style.display = "none";
this.ed.body.innerHTML = this.textarea.value;
}
},
Exec: function(o, cmd, para) {
try {
this.ed.execCommand(cmd, false, para);
this.Show();
}
catch(err) {
return;
}
},
InsertImage: function(o) {
if (Sys.IE) { ! this.isfocus && this.iframe.contentWindow.focus();
this.rang = this.ed.selection.createRange();
}
this.lightbox.Show();
this.makebody(this.Imagepopoup, "350px", "插入图片", "InsertImage", "Imagepopoup");
},
CreateLink: function(o) {
if (Sys.IE) this.rang = this.ed.selection.createRange();
this.lightbox.Show();
this.makebody(this.Linkpopoup, "350px", "插入连接", "CreateLink", "Linkpopoup");
},
Fontcolor: function(o) {
var self = this;
if (!this.fontcolorpopup) {
var color = new popoup({
width: "210px",
title: "颜色选择"
});
this.fontcolorpopup = color.container;
var pos = Getpos(o);
Css(color.container, {
left: pos.x + "px",
top: pos.y + o.offsetHeight + "px"
});
var bgcolor = ["00", "33", "66", "99", "CC", "FF", "00", "33", "66", "99", "CC", "FF"];
$$(color.container, "div")[1].appendChild(createtab(12, 18,
function(tab) {
Attr(tab, {
cellPadding: 0,
cellSpacing: 1,
border: 0,
bgColor: "#333333"
});
},
null,
function(i, j, td) {
var color = i Attr(td, {
width: 10,
height: 10,
unselectable: "on"
});
td.style.backgroundColor = color;
addListener(td, 'click', Bind(self, self.Execa, color, "fontColor"));
addListener(td, 'mousedown', BindAsEventListener(self, self.Bubble));
}))
}
else this.fontcolorpopup.style.display = "block";
this.Fpop = Bind(this, this.Hide);
addListener(this.ed, 'click', this.Fpop);
addListener(document, 'mousedown', this.Fpop);
},
Expression: function(o) {
var self = this;
if (!this.facebgpopup) {
var expr = new popoup({
width: "190px",
title: "插入表情"
});
this.facebgpopup = expr.container;
var pos = Getpos(o);
Css(expr.container, {
left: pos.x + "px",
top: pos.y + o.offsetHeight + "px"
});
$$(expr.container, "div")[1].appendChild(createtab(1, this.option.facebg.length,
function(tab) {
Attr(tab, {
cellPadding: 0,
cellSpacing: 1,
border: 0,
bgColor: "#FFFFFF"
});
},
null,
function(i, j, td) {
Css(td, {
backgroundImage: "url(http://album.hi.csdn.net/app_uploads/wtcsy/20090719/220510752.p.gif)",
backgroundPosition: self.option.facebg[j].bgimg
});
Attr(td, {
width: self.option.facebg[i].wl,
height: self.option.facebg[i].wl,
unselectable: "on"
});
addListener(td, 'click', Bind(self, self.Execa, self.option.facebg[j].src, "Expression"));
addListener(td, 'mousedown', BindAsEventListener(self, self.Bubble))
}));
}
else this.facebgpopup.style.display = "block";
this.Fpop = Bind(this, this.Hide);
addListener(this.ed, 'click', this.Fpop);
addListener(document, 'mousedown', this.Fpop);
},
Layout: function() {
var child = this.ed.body.childNodes;
for (var i = 0, l = child.length; i if (child[i].nodeName == "DIV" || child[i].nodeName == "P") child[i].style.textIndent = child[i].style.textIndent == "2em" ? "": "2em";
}
},
Fontsize: function(o) {
if (!this.fontsizepopup) {
var size = new popoup({
width: "210px",
title: "字号"
}),
a;
this.fontsizepopup = size.container;
var pos = Getpos(o);
Css(size.container, {
left: pos.x + "px",
top: pos.y + o.offsetHeight + "px"
});
for (var i = 0, l = this.option.fontsizedata.fontSize.length; i a = create("a", $$(size.container, "div")[1]);
a.className = "c" + (i + 1);
a.setAttribute("href", "javascript:void(0);")
a.innerHTML = this.option.fontsizedata.fontSize[i];
addListener(a, "click", Bind(this, this.Execa, i, "fontSize"));
addListener(a, 'mousedown', BindAsEventListener(this, this.Bubble));
}
} else this.fontsizepopup.style.display = "block";
this.Fpop = Bind(this, this.Hide);
addListener(this.ed, 'click', this.Fpop);
addListener(document, 'mousedown', this.Fpop);
},
FontName: function(o) {
if (!this.fontnamepopup) {
var name = new popoup({
width: "200px",
title: "字体"
}),
a;
this.fontnamepopup = name.container;
var pos = Getpos(o);
Css(name.container, {
left: pos.x + "px",
top: pos.y + o.offsetHeight + "px"
});
for (var i = 0, l = this.option.fontsizedata.fontname.length; i a = create("a", $$(name.container, "div")[1]);
a.className = "n";
a.setAttribute("href", "javascript:void(0);");
a.innerHTML = this.option.fontsizedata.fontname[i];
addListener(a, "click", Bind(this, this.Execa, this.option.fontsizedata.fontname[i], "fontname"));
addListener(a, 'mousedown', BindAsEventListener(this, this.Bubble));
}
} else this.fontnamepopup.style.display = "block";
this.Fpop = Bind(this, this.Hide);
addListener(this.ed, 'click', this.Fpop);
addListener(document, 'mousedown', this.Fpop);
},
makebody: function(o, w, t, f, n) {
if (!o) {
var self = this;
this[n] = new popoup({
width: w,
title: t
});
this[n].pos();
$$(this[n].container, "div")[1].innerHTML = "
连接地址 
学习js在线html(富文本,所见即所得)编辑器_基础知识 学习js在线html(富文本,所见即所得)编辑器_基础知识
"
this[n].elm = [$$(this[n].container, "input")[0], $$(this[n].container, "img")[0], $$(this[n].container, "img")[1]];
this[n].elm[0].focus()
addListener(this[n].elm[1], 'click', Bind(this, this.Execa, null, f));
addListener(this[n].elm[2], 'click',
function() {
self.lightbox.Close();
self[n].Close();
});
}
else with(this[n]) {
pos();
Show();
elm[0].value = "";
elm[0].focus();
}
},
Addtable: function() {
if (Sys.IE) { ! this.isfocus && this.iframe.contentWindow.focus();
this.rang = this.ed.selection.createRange();
}
this.lightbox.Show();
if (Sys.IE) this.rang = this.ed.selection.createRange();
if (!this.tablepopup) {
var self = this;
this.tablepopup = new popoup({
width: "300px",
title: "插入表格"
});
this.tablepopup.pos();
$$(this.tablepopup.container, "div")[1].innerHTML = "
行数: 列数:
表格的宽度: px
表行的高度: px
学习js在线html(富文本,所见即所得)编辑器_基础知识 学习js在线html(富文本,所见即所得)编辑器_基础知识
"
var o = $$(this.tablepopup.container, "input");
this.tablepopup.elm = [o[0], o[1], o[2], o[3], $$(this.tablepopup.container, "img")[0], $$(this.tablepopup.container, "img")[1]];
addListener(this.tablepopup.elm[4], 'click', Bind(this, this.Execa, null, "CreateTable"));
addListener(this.tablepopup.elm[5], 'click',
function() {
self.lightbox.Close();
self.tablepopup.Close();
});
}
else with(this.tablepopup) {
pos();
Show();
elm[0].focus();
}
this.Fpop = Bind(this, this.Hide);
addListener(this.ed, 'click', this.Fpop);
addListener(document, 'mousedown', this.Fpop);
},
Hide: function(o) {
this.facebgpopup && (this.facebgpopup.style.display = "none");
this.fontsizepopup && (this.fontsizepopup.style.display = "none");
this.fontnamepopup && (this.fontnamepopup.style.display = "none");
this.fontcolorpopup && (this.fontcolorpopup.style.display = "none");
removeListener(this.ed, 'click', this.Fpop);
removeListener(document, 'mousedown', this.Fpop);
},
Bubble: function(e) {
if (Sys.IE) {
e.cancelBubble = true
} else {
e.stopPropagation()
}
},
Execa: function(num, stamp) {
var exec = {
fontname: function() {
this.fontnamepopup.style.display = "none";
this.ed.execCommand('FontName', false, num);
},
fontSize: function() {
this.fontsizepopup.style.display = "none";
this.ed.execCommand("FontSize", false, num + 1)
},
fontColor: function() {
this.fontcolorpopup.style.display = "none";
this.ed.execCommand("ForeColor", false, num);
},
CreateLink: function() {
this.lightbox.Close();
this.Linkpopoup.Close();
if (this.Linkpopoup.elm[0].value == "") return;
if (Sys.IE) {
this.rang.execCommand("CreateLink", false, this.Linkpopoup.elm[0].value);
this.rang.parentElement().target = "_blank ";
}
else {
this.ed.execCommand("CreateLink", false, this.Linkpopoup.elm[0].value);
this.rang = this.iframe.contentWindow.getSelection().getRangeAt(0);
this.rang.commonAncestorContainer.parentNode.target = "_blank ";
}
},
InsertImage: function() {
this.lightbox.Close();
this.Imagepopoup.Close();
if (this.Imagepopoup.elm[0].value == "") return;
Sys.IE ? this.rang.execCommand("InsertImage", false, this.Imagepopoup.elm[0].value) : this.ed.execCommand("InsertImage", false, this.Imagepopoup.elm[0].value);
},
Expression: function() {
this.facebgpopup.style.display = "none";
Sys.IE && (this.iframe.contentWindow.focus());
this.ed.execCommand("InsertImage", false, num);
},
CreateTable: function() {
this.lightbox.Close();
this.tablepopup.Close();
var o = this.tablepopup.elm,
p = null;
if (Sys.IE) {
this.rang.execCommand("InsertImage", false, "http://xxx.com/xxxxx.gif");
p = this.rang.parentElement();
}
else {
this.ed.execCommand("InsertImage", false, "http://xxx.com/xxxxx.gif");
p = this.iframe.contentWindow.getSelection().getRangeAt(0).commonAncestorContainer;
}
var tab = createtab(o[0].value, o[1].value,
function(tab) {
Attr(tab, {
cellPadding: 0,
cellSpacing: 1,
border: 0,
bgColor: "#CCCCCC",
width: o[2].value
});
},
null,
function(i, j, td) {
td.height = o[3].value;
td.width = o[2].value / o[1].value;
td.style.backgroundColor = "#FFFFFF"
},
this.ed);
var imgs = p.getElementsByTagName("img");
for (var i = 0, l = p.childNodes.length; i if (imgs[i].src == "http://xxx.com/xxxxx.gif") {
p.replaceChild(tab, imgs[i])
}
}
p.insertBefore(this.ed.createElement("br"), tab.nextSibling);
}
};
Bind(this, exec[stamp])();
}
});
var popoup = new Class({
options: {
width: "200px",
title: "标题"
},
initialize: function(options) {
this.container = create("div", document.body);
Extend(this.options, options);
this.title = this.options.title;
this.container.className = "pp";
this.container.style.width = this.options.width;
this.container.innerHTML = "
";
this.w = this.container.offsetWidth;
this.h = this.container.offsetHeight;
$$(this.container, "span")[0].innerHTML = this.title;
},
pos: function() {
var str = "left:" + (Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth) - this.w) / 2 + "px;top:" + ((Math.min(document.documentElement.scrollHeight, document.documentElement.clientHeight) - this.h) / 2 + document.documentElement.scrollTop) + "px"
Css(this.container, str);
},
Show: function() {
this.container.style.display = "";
},
Close: function() {
this.container.style.display = "none";
}
})
var LightBox = {
obj: null,
config: {
Color: "#fff",
Opacity: 80,
zIndex: 5
},
init: function(options) {
Extend(this.config, options || {});
Extend(this, this.config);
delete this.config;
this.obj = document.body.insertBefore(document.createElement("div"), document.body.childNodes[0]);
var str = "display:none; z-index:" + this.zIndex + ";left:0px;top:0px;position:fixed;width:100%;height:100%;background-color:" + this.Color + (Sys.IE ? ";filter : alpha(opacity:" + this.Opacity + ")": ";opacity :" + this.Opacity / 100);
Css(this.obj, str);
if (Sys.IE6) {
this.obj.style.position = "absolute";
var _self = this;
this._resize = function() {
_self.obj.style.width = Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth) + "px";
_self.obj.style.height = Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight) + "px";
};
this.obj.innerHTML = '';
}
return this;
},
Show: function() {
if (Sys.IE6) {
this._resize();
addListener(window, "resize", this._resize);
}
this.obj.style.display = "block";
},
Close: function() {
this.obj.style.display = "none";
if (Sys.IE6) removeListener(window, "resize", LightBox._resize);
}
}
window.onload = function() {
var data = [{
Class: "span0",
hover: "span0_hover",
title: "加粗",
action: "Exec",
args: "bold"
},
{
Class: "span1",
hover: "span1_hover",
title: "斜体",
action: "Exec",
args: "Italic"
},
{
Class: "span2",
hover: "span2_hover",
title: "下划线",
action: "Exec",
args: "Underline"
},
{
Class: "span3",
hover: "span3_hover",
title: "字号",
action: "Fontsize",
args: null
},
{
Class: "span4",
hover: "span4_hover",
title: "字体",
action: "FontName",
args: null
},
{
Class: "span5",
hover: "span5_hover",
title: "文字颜色",
action: "Fontcolor",
args: null
},
{
Class: "span6",
hover: "span6_hover",
title: "插入链接",
action: "CreateLink",
args: null
},
{
Class: "span7",
hover: "span7_hover",
title: "剪贴",
action: "Exec",
args: "Cut"
},
{
Class: "span8",
hover: "span8_hover",
title: "复制",
action: "Exec",
args: "Copy"
},
{
Class: "span9",
hover: "span9_hover",
title: "左对齐",
action: "Exec",
args: "JustifyLeft"
},
{
Class: "span10",
hover: "span10_hover",
title: "居中对齐",
action: "Exec",
args: "JustifyCenter"
},
{
Class: "span11",
hover: "span11_hover",
title: "右对齐",
action: "Exec",
args: "JustifyRight"
},
{
Class: "span12",
hover: "span12_hover",
title: "项目符号",
action: "Exec",
args: "InsertUnorderedList"
},
{
Class: "span13",
hover: "span13_hover",
title: "编号",
action: "Exec",
args: "InsertOrderedList"
},
{
Class: "span14",
hover: "span14_hover",
title: "插入表格",
action: "Addtable",
args: null
},
{
Class: "span15",
hover: "span15_hover",
title: "减少缩进",
action: "Exec",
args: "Outdent"
},
{
Class: "span16",
hover: "span16_hover",
title: "增加缩进",
action: "Exec",
args: "Indent"
},
{
Class: "span17",
hover: "span17_hover",
title: "清除样式",
action: "Exec",
args: "RemoveFormat"
},
{
Class: "span18",
hover: "span18_hover",
title: "插入图片",
action: "InsertImage",
args: null
},
{
Class: "span19",
hover: "span19_hover",
title: "插入表情",
action: "Expression",
args: null
},
{
Class: "span20",
hover: "span20_hover",
title: "自动排版",
action: "Layout",
args: null
}];
new Editer($('ss'), data, LightBox.init());
}