JS/JQuery execCommand 问题
我在 execCommand 方面遇到了麻烦(完整),所以非常感谢您的帮助 - 我毫不怀疑我正在吠叫错误的树,但是......无论如何
我有一个像这样的 div
<div class="editable" id="editor" contenteditable="true">
<2>Some text in here</h2> blah blah blah ...
</div>
这是“可编辑的”即 文档。 designMode = 'on';
- 它获得焦点的“状态”。在模糊时,它更改为 document.designMode = 'off';
我有一个“测试按钮”
<input type="button" id="bold" value="Bold">
,当“单击”时,“突出显示的文本”会变成粗体 - 因此 execCommand
到目前为止,我有这样的东西:
function getSelected() {
if(window.getSelection) { return window.getSelection(); }
else if(document.getSelection) { return document.getSelection(); }
else {
var selection = document.selection && document.selection.createRange();
if(selection.text) { return selection.text; }
return false;
}
return false;
}
$('#bold').click(function(){
var selection = getSelected();
alert(selection);
});
警报(粗体单击)确实给了我突出显示/选定的文本,但我无法弄清楚如何将其“变成粗体”。我想我需要访问innerHTML之类的东西?
非常感谢您的帮助 - 提前致谢。哦,我不想使用 i-frame 或 textarea
I am having trouble (complete) with execCommand so you help much appreciated - I have no doubt I am barking up the wrong tree but ..... anyway
I have a div like this
<div class="editable" id="editor" contenteditable="true">
<2>Some text in here</h2> blah blah blah ...
</div>
That is "editable" i.e. document.designMode = 'on';
- it get's this "state" on focus. On blur it changes to document.designMode = 'off';
I have a "test button"
<input type="button" id="bold" value="Bold">
That when "clicked" makes the "highlighted text" bold - hence execCommand
So far I have something like this:
function getSelected() {
if(window.getSelection) { return window.getSelection(); }
else if(document.getSelection) { return document.getSelection(); }
else {
var selection = document.selection && document.selection.createRange();
if(selection.text) { return selection.text; }
return false;
}
return false;
}
$('#bold').click(function(){
var selection = getSelected();
alert(selection);
});
The alert (bold click) does give me the highlighted/selected text but I cannot work out how to "turn it" bold. I guess I need to access the innerHTML or something?
Help much appreciated - thanks in advance. OH and I do not want to use either an i-frame or a textarea
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我强烈建议使用 Rangy 来处理文本选择。
您可以使用 CSS 类应用程序模块将文本加粗 (现场演示)。
I strongly recommend using Rangy for dealing with text selection.
You can use the CSS Class Applier Module to bold the text (live demo).