javascript实现HTML在线编辑器

javascript实现HTML在线编辑器  
以前一直不知道好多网站上所说的在线编辑器是怎么回事,后来在文档里发现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="https://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" οnclick="Black()" /></TD>
<TD><input type="button" value="I" name="Italic" οnclick="Italic()" /></TD>
<TD><input type="button" value="U" name="UnderLine" οnclick="UnderLine()" /></TD>
   <TD><input type="button" value="UL" name="UnorderList" οnclick="UnorderList()" /></TD>
   <TD><input type="button" value="OL" name="OrderList" οnclick="OrderList()" /></TD>
<TD><input type="button" value="左" name="Outdent" οnclick="Outdent()" /></TD>
<TD><input type="button" value="右" name="Indent" οnclick="Indent()" /></TD>
<TD><input type="button" value="图" name="Image" οnclick="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" οnclick="Add()" />&nbsp;&nbsp;
<input type="button" value=" 预   览 " name="Preview" οnclick="Preview()" />&nbsp;&nbsp;
<input type="button" value=" 源代码 " name="Source" οnclick="Source()" />
</BODY>
</HTML>


三、后记:

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

contenteditable="true"



document.execCommand(command, false, value);
关于 document 的一些方法,可以查看MS的文档。
execCommand 的一些命令也可以在文档里找到,下面列出一些:
execCommand(command, false, value); 中的 command 可以是以下这些:




BackColor
Sets or retrieves the background color of the current selection.

当前选择设置重新获得背景颜色

Bold
Toggles the current selection between bold and nonbold.

宽字体和非宽字体进行切换

ClearAutocompleteForForms
Clears saved forms data.

清除保存的forms数据

Copy
Copies the current selection to the clipboard.

复制当前选择到剪贴板

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

为但前选择地方,重置书签锚点,或者创建书签锚点

CreateLink
Retrieves the URL of a hyperlink or creates a hyperlink on the current selection.

为当前选择部分,重置超级链接地址,或者新建超级链接地址

Cut
Copies the current selection to the clipboard and then deletes it.

剪切当前内容到剪贴板

Delete
Deletes the current selection.

删除当前选择

FontName
Sets or retrieves the font for the current selection.

设置和重置当前选择的字体

FontSize
Sets or retrieves the font size for the current selection.

为当前选择部分,设置和重置字体大小

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

为当前选择部分,设置和重置文本颜色

FormatBlock
Sets or retrieves the current block format tag.

设置和重置当前块格式标签

Indent
Increases the indent of the selected text by one indentation increment.

为选择部分增加一个缩进

InsertButton
Overwrites a button control on the current selection.

覆写一个按钮控制当前选择

InsertFieldset
Overwrites a box on the current selection.

为当前选择覆写一个盒子

InsertHorizontalRule
Overwrites a horizontal line on the current selection.

为当前选择部分覆写水平线

InsertIFrame
Overwrites an inline frame on the current selection.

为当前选择部分覆写内联框架

InsertImage
Overwrites an image on the current selection.

为当前选择部分覆写图片

InsertInputButton
Overwrites a button control on the current selection.

覆写一个按钮控制当前选择

InsertInputCheckbox
Overwrites a check box control on the current selection.

为当前选择部分覆写一个复选框

InsertInputFileUpload
Overwrites a file upload control on the current selection.

为当前选择部分覆写一个上传控制

InsertInputHidden
Inserts a hidden control on the current selection.

为当前选择部分覆写一个隐藏域

InsertInputImage
Overwrites an image control on the current selection.

为当前选择部分覆写一个图片

InsertInputPassword
Overwrites a password control on the current selection.

为当前选择部分覆写一个密码输入

InsertInputRadio
Overwrites a radio control on the current selection.

为当前选择部分覆写一个单选框

InsertInputReset
Overwrites a reset control on the current selection.

为当前选择部分覆写一个重置

InsertInputSubmit
Overwrites a submit control on the current selection.

为当前选择部分覆写一个提交

InsertInputText
Overwrites a text control on the current selection.

为当前选择部分覆写一个文本

InsertMarquee
Overwrites an empty marquee on the current selection.

为当前选择部分覆写一个选取框

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

为当前选择部分设置通常格式块或整齐排列

InsertParagraph
Overwrites a line break on the current selection.

为当前选择部分覆写一个线

InsertSelectDropdown
Overwrites a drop-down selection control on the current selection.

为当前选择部分覆写一个顺序向下的选择控制

InsertSelectListbox
Overwrites a list box selection control on the current selection.

为当前选择部分覆写一个列表框

InsertTextArea
Overwrites a multiline text input control on the current selection.

为当前选择部分覆写一个多行文本输入

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

为当前选择部分设置通常格式块或整齐排列

Italic
Toggles the current selection between italic and nonitalic.

设置斜体和取消斜体

JustifyCenter
Centers the format block in which the current selection is located.

为当前选择部分设置设置居中

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

为当前选择部分设置居左

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

为当前选择部分设置居右

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

为当前选择部分减少一个缩进

OverWrite
Toggles the text-entry mode between insert and overwrite.

在文本中间插入并且覆盖

Paste
Overwrites the contents of the clipboard on the current selection.

把剪贴板中内容暂帖到当前选择部分

Refresh
Refreshes the current document.

刷新当前文档

RemoveFormat
Removes the formatting tags from the current selection.

从当前选择的部分中删除格式标签

SelectAll
Selects the entire document.

选择全部文档

SaveAs
Saves the current Web page to a file.

保存当前web页面到文件

UnBookmark
Removes any bookmark from the current selection.

从当前选择的部分删除书签

Underline
Toggles the current selection between underlined and not underlined.

从当前选择的部分放置下划线和取消下划线

Unlink
Removes any hyperlink from the current selection.

从当前选择的部分删除超级链接

Unselect
Clears the current selection.

清除当前选择



2D-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 清除当前选中区的选中状态。

document.execCommand(sCommand[,交互方式, 动态参数])

2D-Position;document.execCommand("2D-Position","false","true");使绝对定位的对象可直接拖动;ie5.5

AbsolutePosition;document.execCommand("AbsolutePosition","false","true");使对象定位变成绝对定位;ie5.5

BackColor;document.execCommand("BackColor","false",sColor);设置背景颜色;ie4.0

BlockDirLTR;none;使块级元素排版方式为从左到右?;不支持

BlockDirRTL;none;使块级元素排版方式为从右到左?;不支持 Bold;document.execCommand("Bold","false",null);使选中区域的文字加粗;ie4.0

BrowseMode;none;设置浏览器模式?;不支持 Copy;

document.execCommand("Copy","false",null);复制选中的文字到剪贴板;ie4.0 CreateBookmark;document.execCommand("CreateBookmark","false",sAnchorName);设置指定锚点为书签;ie4.0

CreateLink;document.execCommand("CreateLink","false",sLinkURL);将选中文本变成超连接,若第二个参数为true,会出现参数设置对话框;ie4.0

Cut;document.execCommand("Cut","false",null);剪贴选中的文字到剪贴板;ie4.0

Delete;document.execCommand("Delete","false",null);删除选中的文字;ie4.0

DirLTR;none;排版方式为从左到右?;不支持 DirRTL;none;排版方式为从右到左?;不支持

EditMode;none;设置编辑模式?;不支持

FontName;document.execCommand("FontName","false",sFontName);改变选中区域的字体;ie4.0

FontSize;document.execCommand("FontSize","false",sSize|iSize);改变选中区域的字体大小;ie4.0

ForeColor;document.execCommand("ForeColor","false",sColor);设置前景颜色;ie4.0

FormatBlock;document.execCommand("FormatBlock","false",sTagName);设置当前块的标签名;ie4.0

<HTML>

  

  

<HEAD>

<SCRIPT LANGUAGE="JScript">

/*

*該function執行copy指令

*/

function fn_doufucopy() {

edit.select();

document.execCommand('Copy');

}

/*

*該function執行paste指令

*/

function fn_doufupaste() {

tt.focus();

document.execCommand('paste');

}

__>

</SCRIPT>

</head>

<body>

<input id=edit value=范例><br>

<button οnclick=fn_doufucopy()>Copy</button>

<button οnclick=fn_doufupaste()>paste</button><br>

<textarea id=tt rows=10 cols=50></textarea>

</body>

</html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=big5">

<meta name="GENERATOR" content="Microsoft FrontPage 4.0">

<meta name="ProgId" content="FrontPage.Editor.Document">

<title>execCommand整理</title>

<script language=javascript>

/*

*該function用來創建一個超鏈結

*/

function fn_creatlink()

{

document.execCommand('CreateLink',true,'true');//彈出一個對話框輸入URL

//document.execCommand('CreateLink',false,'http://www.51js.com');

}

/*

*該function用來將選中的區塊設為指定的背景色

*/

function fn_change_backcolor()

{

document.execCommand('BackColor',true,'#FFbbDD');//true或false都可以

}

/*

*該function用來將選中的區塊設為指定的前景色,改變選中區塊的字體大小,改變字體,字體變粗變斜

*/

function fn_change_forecolor()

{

//指定前景色

document.execCommand('ForeColor',false,'#BBDDCC');//true或false都可以

//指定背景色

document.execCommand('FontSize',false,7); //true或false都可以

//字體必須是系統支持的字體

document.execCommand('FontName',false,'標楷體'); //true或false都可以

//字體變粗

document.execCommand('Bold');

//變斜體

document.execCommand('Italic');

}

/*

*該function用來將選中的區塊加上不同的線條

*/

function fn_change_selection()

{

//將選中的文字加下劃線

document.execCommand('Underline');

//在選中的文字上劃粗線

document.execCommand('StrikeThrough');

//將選中的部分文字變細

document.execCommand('SuperScript');

//將選中區塊的下劃線取消掉

document.execCommand('Underline');

}

/*

*該function用來將選中的區塊排成不同的格式

*/

function fn_format()

{

//有序列排列

document.execCommand('InsertOrderedList');

//實心無序列排列

document.execCommand('InsertUnorderedList');

//空心無序列排列

document.execCommand('Indent');

}

/*

*該function用來將選中的區塊剪下或是刪除掉

*/

function fn_CutOrDel()

{

//刪除選中的區塊

//document.execCommand('Delete');

//剪下選中的區塊

document.execCommand('Cut');

}

/*

*該function用來將選中的區塊重設為一個相應的物件

*/

function fn_InsObj()

{

/*

******************************************

* 以下指令都是為選中的區塊重設一個object;

* 如沒有特殊說明,第二個參數true或false是一樣的;

* 參數三表示為該object的id;

* 可以用在javascript中通過其指定的id來控制它

******************************************

*/

/*重設為一個button(InsertButton和InsertInputButtong一樣,

隻不前者是button,後者是input)*/

/*document.execCommand('InsertButton',false,"aa"); //true或false無效

document.all.aa.value="風舞九天";*/

//重設為一個fieldset

/*document.execCommand('InsertFieldSet',true,"aa");

document.all.aa.innerText="刀劍如夢";*/

//插入一個水平線

//document.execCommand('InsertHorizontalRule',true,"aa");

//插入一個iframe

//document.execCommand('InsertIFrame',true,"aa");

//插入一個InsertImage,設為true時需要圖片,false時不需圖片

//document.execCommand('InsertImage',false,"aa");

//插入一個checkbox

//document.execCommand('InsertInputCheckbox',true,"aa");

//插入一個file類型的object

//document.execCommand('InsertInputFileUpload',false,"aa");

//插入一個hidden

/*document.execCommand('InsertInputHidden',false,"aa");

alert(document.all.aa.id);*/

//插入一個InputImage

/*document.execCommand('InsertInputImage',false,"aa");

document.all.aa.src="F-a10.gif";*/

//插入一個Password

//document.execCommand('InsertInputPassword',true,"aa");

//插入一個Radio

//document.execCommand('InsertInputRadio',false,"aa");

//插入一個Reset

//document.execCommand('InsertInputReset',true,"aa");

//插入一個Submit

//document.execCommand('InsertInputSubmit',false,"aa");

//插入一個input text

//document.execCommand('InsertInputText',false,"aa");

//插入一個textarea

//document.execCommand('InsertTextArea',true,"aa");

//插入一個 select list box

//document.execCommand('InsertSelectListbox',false,"aa");

//插入一個single select

document.execCommand('InsertSelectDropdown',true,"aa");

//插入一個line break(硬回車??)

//document.execCommand('InsertParagraph');

//插入一個marquee

/*document.execCommand('InsertMarquee',true,"aa");

document.all.aa.innerText="bbbbb";*/

//用於取消選中的陰影部分

//document.execCommand('Unselect');

//選中頁面上的所有元素

//document.execCommand('SelectAll');

}

/*

*該function用來將頁面保存為一個文件

*/

function fn_save()

{

//第二個參數為欲保存的文件名

document.execCommand('SaveAs','mycodes.txt');

//打印整個頁面

//document.execCommand('print');

}

</script>

</head>

<body>

<input type=button value="創建CreateLink" οnclick=fn_creatlink()><br>

<input type=button value="改變文字背景色" οnclick=fn_change_backcolor()><br>

<input type=button value="改變文字前景色" οnclick=fn_change_forecolor()><br>

<input type=button value="給文字加線條" οnclick=fn_change_selection()><br>

<input type=button value="改變文字的排列" οnclick=fn_format()><br>

<input type=button value="刪除或剪下選中的部分" οnclick=fn_CutOrDel()><br>

<input type=button value="插入Object" οnclick=fn_InsObj()><br>

<input type=button value="保存或打印文件" οnclick=fn_save()><br>

<input type=button value="測試Refresh屬性" οnclick="document.execCommand('Refresh')">

</body>

</html>

普通的方式是激活一个<iframe>进入编辑状态,命令如下

IframeNamer.document.designMode="On"

字体--宋体、黑体、楷体等

execCommand("fontname","",字体)

字号--字号大小

execCommand("fontsize","",字号)

加重

execCommand("Bold")

斜体

execCommand("Italic")

下划线

execCommand("Underline")

删除线

execCommand("StrikeThrough")

上标

execCommand("SuperScript")

下标

execCommand("SubScript")

有序排列--数字序号

execCommand("InsertOrderedList")

无序排列--圆点序号

execCommand("InsertUnorderedList")

向前缩进

execCommand("Outdent")

向后缩进

execCommand("Indent")

居左

execCommand("JustifyLeft")

居右

execCommand("JustifyRight")

居中

execCommand("JustifyCenter")

剪切

execCommand("Cut")

拷贝

execCommand("Copy")

粘贴

execCommand("Paste")

覆盖

execCommand("Overwrite")

取消操作--IE5.0以后可以无限取消

execCommand("Undo")

重复操作

execCommand("Redo")

设置链接--若按以下写法,在IE5.0版本中会激活一个内建窗口,可以完成输入链接的功能,而且还可以选择MAILTO、FTP等各种链接类型,比较方便

execCommand("CreateLink")

在IE4.0中,没有内建链接输入窗口,所以就需要用以下方式嵌入链接

execCommand("CreateLink","",TURL)

插入图片--由于IE中嵌入的可编控件是针对本地资源的,所以其默认的图片资源来自本地,所以基于WEB内容的编辑最好自己做输入框,然后用如下命令实现。

execCommand("InsertImage","",ImgURL)

字体颜色

execCommand("ForeColor","",CColor)

标签:
作者 pqzemily 阅读全文 |  评论(2)  | 人气(6) |  引用(0)  | 推荐 |  


2008.07.01 14:38:00 
近期目标  
spring/memcached/Ajaxpro/log4net

For DotNet
标签:
作者 pqzemily 阅读全文 |  评论(0)  | 人气(2) |  引用(0)  | 推荐 |  


2007.11.14 18:00:00 
js类创建, 类继承小结  
js类创建, 类继承小结

<html>
<script ></script>
<script>
//建立唯一类对象的方法:
//Person是一个匿名类的唯一实例化 对象, 故它不是一个类, 不能够再用new 来示例化!!
var Person={                                      //注意: 没有 propertype 属性,
  name:'person',
  getName:function(){return 'person';}
};
//建立类
//方法一:    常规
var One = function(){
  this.name = 'One person';                       //非静态属性
    /*在类里访问属性或方法比须用this*/
  this.getName = function(){return this.name;};   //非静态方法
}
One.sex = "超女";                                 //静态属性
One.getSex = function(){return this.sex};         //静态方法
//if(One.prototype) alert("One 有 prototype");     //这样的类含有 prototype 属性
var tmp = new One();                                //实例化对象
//alert("姓名 : " + tmp.getName());                 //调用非静态方法
//alert("性别 : " + One.getSex());                  //调用静态方法

//方法二:    借助prototype.js
var MyClass = Class.create();                     //创建, 但无任何属性, 方法
Object.extend(MyClass, {                          //扩展一些静态属性, 方法
      //当然也可以用方法一中的方法添加静态属性, 成员函数
    qq : "103430585",
    getQq : function(){return this.qq;}
});
Object.extend(MyClass.prototype, {                //扩展一些非静态属性, 方法
    initialize : function(){   
    //构造函数, 必须实现且必须为非静态函数, 由Class.create()调用, 可以有参数,
        alert("MyClass is initializing ...");
    },
    email : "btpka3@163.com",
    getEmail : function(){return this.email;}
});
//alert(MyClass.getQq());         //调用静态方法, 不能用实例化对象去调用该方法!
//var tmp_mc = new MyClass();     //实例化对象
//alert(tmp_mc.getEmail());       //调用非静态方法, 不能用类名去调用该方法!!!

var father = Class.create();
Object.extend(father.prototype, {
    initialize : function(){/*alert("init_father");*/},  
    say:function(){return "father: say() : nonstatic"; }
});
father.say = function(){return "father: say() : static";};

var tmp_f = new father();
//alert("father.say() = " + father.say() +"/ntmp_f.say() = "+ tmp_f.say());
//显示:  father.say() = father: say() : static
//       tmp_f.say() = father: say() : nonstatic
var sun = Class.create();
LABEL_MARK:
Object.extend(sun.prototype, {      //
    initialize : function(){/*alert("init_sun");*/},
    say: function(){return "sun : say() : nonstatic"; }
});
Object.extend(sun, {
    say: function(){return "sun : say() : static";}
});
var tmp_s;
//以下是在子类已经有自己的静态方法后, 再继承父类后的显示, 四种继承方式中,
//在 IE 7.0 与 FF 1.0.7 中 只有第一中的结果不一致, 其他三种均一致!
//但是有一个简单的方法可以避免被父类的同名方法覆盖, 那就是
// 先 Class.create(); 再Object.extend()继承父类,
//最后再Object.extend()扩充 或 重写 子类的动, 静态方法

/* 第一种: 子类静态属性, 方法继承父类的静态方法 (同名属性被父类覆盖)
Object.extend(sun, father);
tmp_s = new sun();
alert("after Object.extend(sun, father);/n"
    + "sun.say() = "+sun.say()+"/n"
    + "tmp_s.say() = "+tmp_s.say());
*/
//显示:  after Object.extend(sun, father);
//       sun.say() = father: say() : static
//       tmp_s.say() = sun : say() : nonstatic //IE中显示,
//最后一句在 FF 中是:  father: say() : nonstatic
//原因: prototype.js 中的函数 Object.extend() 在IE和FF中的执行不一致!!
//      FF 比 IE 多了一步: 将 sun[prototype] = father[prototype]
/* 第二种: 子类静态属性, 方法继承父类非静态方法,(同名属性被父类覆盖)
Object.extend(sun, father.prototype);
tmp_s = new sun();
alert("after Object.extend(sun, father.prototype);/n"
    + "sun.say() = "+sun.say()+"/n"
    + "tmp_s.say() = "+tmp_s.say());
*/
//显示:  after Object.extend(sun, father.prototype);
//       sun.say() = father: say() : nonstatic
//       tmp_s.say() = sun : say() : nonstatic 
/*第三种: 子类非静态属性, 方法继承父类静态属性, 方法, (同名属性被父类覆盖)
Object.extend(sun.prototype, father);
tmp_s = new sun();
alert("after Object.extend(sun.prototype, father);/n"
    + "sun.say() = "+sun.say()+"/n"
    + "tmp_s.say() = "+tmp_s.say());
*/
//显示: after Object.extend(sun.prototype, father);
//      sun.say() = sun : say() : static
//      tmp_s.say() = father: say() : static
//但是根据第一种测试知: sun.prototype.prototype = father.prototype;
//故 在FF中可以 通过 sun.prototype.prototype.say() 调用父类的 非静态 say()方法;

/*第四种: 子类非静态属性, 方法继承父类非静态属性, 方法 (同名属性被父类覆盖)
Object.extend(sun.prototype, father.prototype);
tmp_s = new sun();
alert("after Object.extend(sun.prototype, father.prototype);/n"
    + "sun.say() = "+sun.say()+"/n"
    + "tmp_s.say() = "+tmp_s.say());
*/
//显示: after Object.extend(sun.prototype, father.prototype
//      sun.say() = sun : say() : static
//      tmp_s.say() = father: say() : nonstatic
</script>
</html>


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值