document.ExecCommand insertHTML在Safari中插入跨度和怪异行为

问题描述 投票:1回答:1

[当尝试使用insertHTML时

document.execCommand('insertHTML', false, `<b id="searchId${numberID}" style="background-color: ${color};" >${text}</b>`

在除Safari之外的任何浏览器中都能正常工作。

[示例:如果a标签包含“ Passage”字样,则尝试插入html。但是,仅在Safari中,如果“ Passage”单词位于标签顺序的末尾,或者带有空格和其他文本,则插入类似以下内容的代码

document.execCommand('insertHTML', false, `<span style="background-color: ${color};" >${text}</span>`

---------------示例

Passage1 | OtherTag = Works

通道1 | OtherTag =无效

OtherTag | Passage1 =无效

此功能用于突出显示在许多显示的文档中搜索栏中写入的文本,并且具有锚定功能以遍历所有结果,这需要具有ID。

适用于IE,Firefox,Mozilla,Chrome和Opera。无法在Safari中使用。

更准确的示例:

搜索词“通道”

在除Safari以外的所有浏览器中

<div class="col-8 px-0">
  <p class="badge badge-document">
    <b id="searchId1" style="background-color: rgb(255, 226, 183);">
      Passage
    </b>
   1
  </p>
</div>

在safari中(只有在有空格和其他文本的情况下(Passage1起作用,Passage 1不能起作用,并且如果在这种情况下,Passage是最后一个(Tag 1-标记2-Passage1 / Passage 1)添加此范围(如果是第一个或中间),则将b与所有其他浏览器一样添加。]

<div class="col-8 px-0">
 <p class="badge badge-document">
  <span style="background-color: rgb(255, 226, 183);">
      Passage
  </span>
   1
 </p>
</div>

Safari

Passage1 +不是最后一个标记=添加b块

通道1 +不是最后一个标记=添加没有ID的跨度块

Passage1 +最后一个标记=添加不带ID的跨度块

通道1 +最后一个标记=添加不带ID的跨度块

function insertHTML(text) {
    if (window.find && window.getSelection) {
    document.designMode = "on";
    var sel = window.getSelection();
    sel.collapse(document.body, 0);
    while (window.find(text)) {
    document.execCommand('insertHTML', false, '<b id="searchId1"     style="background-color: red" >Passage</b>');        sel.collapseToEnd();
    }
      document.designMode = "off";
  }
 }
 
<input id="inputSearch" type="search" placeholder="Search" value="Passage">
 
 <button id="button" type="search" onClick="insertHTML(inputSearch.value)"> Search</button>


<p>Passage 1</p>
<p>Tag 2</p>
<p>Tag 3</p>

编辑:在这里找到解决方案:SolutionTLDR:必须将可插入元素包含在父div中。

当尝试使用insertHTML document.execCommand('insertHTML',false,`$ {text}

javascript html safari execcommand inserthtml
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.