我想制作自己的文本编辑器。我正在尝试效仿其他几个成熟的编辑器的例子,并使用隐藏的<textarea>
和可见<iframe>
组合。
我在键入<iframe>
的第一步时遇到了麻烦。我可以让execCommand处理一个内容可编辑的<div>
,例如,使文本加粗,但在<iframe>
上做同样的事情时遇到麻烦。
这是我的 HTML:
<html>
<button type="button" class="btn btn-bold">bold</button>
<textarea id="input" name="input" style="display: none;">Start typing..</textarea>
<iframe frameborder="0" src="javascript:true;" style=""> </iframe>
</html>
这是我的JavaScript:
$(function() {
var currentBtn;
$("#input").focus(function() {
currentBtn = this;
});
$(".btn").on( 'click', '.btn-bold', function(){
var $this=$(this);
if($this.hasClass("btn-bold")){ document.execCommand('bold', false, null);}
$(currentBtn).contents().focus();
});
});
我知道我需要在 iframe 文档而不是父文档上执行 execCommand,但只是不确定如何做到这一点。目前,此代码不允许我抠像 iframe,因此无法测试粗体按钮的效果。
任何想法将不胜感激!
使用 Rangy 并将<b>
环绕在所选内容周围以加粗。您也可以使用此方法执行其他任务。
演示:http://rangy.googlecode.com/svn-history/r511/trunk/demos/core.html
编辑
如何使iframe
可编辑:
window.frames[0].document.getElementsByTagName("body")[0].contentEditable = true;
- http://jsfiddle.net/DerekL/vpCXN/
- http://jsfiddle.net/DerekL/vpCXN/10/- 带粗体按钮
这可能会有所帮助。但它在javascript中,我在谷歌浏览器中运行它。这是代码:
<div>
<input type="button" onClick="bo()" value="B">
<input type="button" onClick="under()" value="U">
<input type='button' onClick="f_size()" value="f_size">
<br>
<iframe name="richTextField" id="richTextField" style="border:#000000 1px solid; width:700px; height:300px;"></iframe><br>
<input type="button" onClick="asd()" value="get_innerhtml"><br>
<textarea name="myTextArea" id="myTextArea" cols="100" rows="14"></textarea>
</div>
<script>
richTextField.document.designMode = 'On';
function bo(){
richTextField.document.execCommand('bold',false,null);
}
function under(){
richTextField.document.execCommand('underline',false,null);
}
function f_size(){
var size = prompt('Enter a size 1 - 7', '');
richTextField.document.execCommand('FontSize',false,size);
}
function asd(){
var text=document.getElementById('richTextField').contentWindow.document.body.innerHTML;
document.getElementById('myTextArea').value=text;
}
</script>