【问题标题】:remove selected text bold and foreground? without execCommand删除选定的文本粗体和前景?没有 execCommand
【发布时间】:2015-10-21 23:50:44
【问题描述】:

我使用 javascript 突出显示或加粗选定的文本范围,它运行良好,但是如果再次单击按钮并且所选范围为粗体或突出显示,我如何使其变为 UNBOLD 和 UNHIGHLIGHTED

我不能使用 doc.execcommand 或 jquery,因为我在 android webview 中使用它,如果我使用 doc.execcommand,该命令需要 1 秒或更长时间才能工作(大文本),如果我使用 jquery,则立即使用 javascript( zepto 或其他),文本需要 AGES 才能在 web 视图中打开,没有它,最多需要 1 或 2 秒。

=(

我用什么来使选定的文本加粗:

function bold() {
    var range               = window.getSelection().getRangeAt(0);
    var selectionContents   = range.extractContents();
    var span                = document.createElement("span");
    span.appendChild(selectionContents);
    span.setAttribute("class","bold");
    span.style.fontWeight  = "bold";

    range.insertNode(span);
  }

和高亮(PS:高亮不会是特定的颜色,用户将通过颜色选择器进行选择,该颜色选择器将返回#xxxxxx

function foreground() {

var range               = window.getSelection().getRangeAt(0);
var selectionContents   = range.extractContents();
var span                = document.createElement("span");

span.appendChild(selectionContents);

span.setAttribute("class","foreground");
span.style.color            = "#" + colorbyUser;

range.insertNode(span);}

我认为粗体/斜体/strike/strikeThrough/下划线只能是css中的一个特定类,我只是添加并删除它(不知道如何删除它,如果它已经为所选范围设置)

但是背景和前景色它不能,因为每个选择(字母/单词或更多)可能不同

抱歉英语不好=x

为 C 微笑编辑

我知道了,但我不知道在这种情况下如何获取元素:

<span class="bold">Hello   <span class="underline">C</span>-<span class="italic">Smile</span></span>

如何删除 HELLO 的粗体,用户只选择 HELLo,但不删除 C-Smile 的粗体??

这可能吗?没有 jquery(需要很长时间才能加载大文档)或 doc.execcomand(需要很长时间才能在大文档中工作)

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    如果您将范围包装成&lt;span class="highlight"&gt; 然后删除你需要打开它 - 获取跨度的内容节点并用它的内容节点替换该跨度。

    这正是 $.unwrap() 在 jQuery 中所做的。

    【讨论】:

    • 嗯,我明白了,你能看一下我的编辑吗?我将阅读 unwrap 函数代码,但我不想使用 jquery 或 doc.execcomando
    猜你喜欢
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多