javascript实现可编辑样式的文本

JavaScript011

javascript实现可编辑样式的文本,第1张

你要的是所见即所得HTML编辑器,简单来说需要几个基本步骤:

1,需要一个可以编辑同时又可显效果的编辑框。textarea不行,它只能用来输入纯文本,不能显示颜色、斜体之类的文字样式,就像记事本。

你可以使用iframe来实现,修改iframe的designMode属性使其可以被编辑。

<iframe id="myEditer" width="100%" height="150px"></iframe>

<script>myEditer.document.designMode = 'on'</script>

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

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

<iframe id="myEditer" width="100%" height="150px"></iframe>

<input type="button" value="加粗" onclick="Bold()">

<script>

myEditer.document.designMode = 'on'

function Bold(){

var sel = myEditer.document.selection.createRange()

alert(sel.text)

}

</script>

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

<iframe id="myEditer" width="100%" height="150px"></iframe>

<input type="button" value="加粗" onclick="Bold()">

<script>

myEditer.document.designMode = 'on'

function Bold(){

var sel = myEditer.document.selection.createRange()

//alert(sel.text)

sel.execCommand("Bold")

}

</script>

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")

把上面的每个用法用按钮来实现,你就已经完成了一个简单的可视文本编辑器。

var defaultFont = 'getComputedSylte' in window?getComputedStyle(document.documentElement)['font-family']:document.documentElement.currentStyle['font-family'] //defaultFont的结果就是浏览器的默认字体名称。至于你说系统的默认字体名称。我认为是无法取到的。