gpt4 book ai didi

javascript - JS/JQuery execCommand 问题

转载 作者:行者123 更新时间:2023-11-28 12:09:09 25 4
gpt4 key购买 nike

我在 execCommand 方面遇到了麻烦(完全),所以非常感谢你的帮助 - 我毫不怀疑我找错了树,但是......无论如何

我有一个像这样的div

<div class="editable" id="editor" contenteditable="true"> 
<2>Some text in here</h2> blah blah blah ...
</div>

这是“可编辑的”,即 document.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

最佳答案

我强烈建议使用Rangy用于处理文本选择。

A cross-browser JavaScript range and selection library. It provides a simple standards-based API for performing common DOM Range and Selection tasks in all major browsers, abstracting away the wildly different implementations of this functionality between Internet Explorer and DOM-compliant browsers.

您可以使用CSS Class Applier Module将文本加粗 ( live demo )。

关于javascript - JS/JQuery execCommand 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5326342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com