【问题标题】:Replace a selected text in contentEditable div with html-React用 html-React 替换 contentEditable div 中的选定文本
【发布时间】:2021-11-23 01:16:25
【问题描述】:

我有一个contectEditable div 和按钮,当我在 div 中选择这样的文本时想要 (CodeSandbox)

然后按下按钮,将选中的文本替换为一个span html 元素,并将选中的文本作为内容。例如,我有这个 React 组件

import {useState} from 'react';

const EdiatbelContent = () => {

    const onClickhandler () => {};
    
    const [html, setHtml] = useState("<p>Hello World!</p>");
    
    return <>
       <div contentEditable="true" dangerouslySetInnerHTML={{ __html: html }}></div>
       <button onClick={onClickHandler}>Bold</button>
    </>

}

export default EditableContent;

我想当我按下按钮时,替换选中的文本(如果有的话),说出上面例子中的单词Hello,用span html元素&lt;span className="text-bold"&gt;Hello&lt;/span&gt;,这样html状态变量就变成了

<p><span className="text-bold">Hello</span> World!</p>

我怎样才能做到这一点?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    如果我的问题正确,您可以使用Selection API 访问用户的选择并使用其属性来实现您想要的。以下是一些可以帮助您入门的代码:

    const onClickHandler = () => {
          // get user's selection
          const selection = window.getSelection();
          // get the start and end index of selection
          // remember user can select backwards
          let startIndex = selection.anchorOffset;
          let endIndex = selection.focusOffset;
          if (startIndex > endIndex) {
            startIndex = selection.focusOffset;
            endIndex = selection.anchorOffset;
          }
          // now get the text before and after the selection
          const beforeSelection = html.substring(0, startIndex);
          const afterSelection = html.substring(endIndex, html.length);
          // and set the html as you see fit
          setHtml(`${beforeSelection}<span className="text-bold">${selection.toString()}</span>${afterSelection}`)
    };
    

    这当然是最基本的形式,需要考虑很多边缘情况。

    【讨论】:

    • 好的,这是一个开始,但是当我将它应用到我上面提供的代码框时,你的代码不起作用。
    • @BlackMath 为什么不呢,怎么了?如果结果文本不正确,则需要将

      标记计入开头,因此由于它是 3 个字符,因此需要在开始和结束索引中添加 3,但这不是一个好方法。您需要区分底层文本和屏幕中显示的 HTML。我只是想给你一个起点,你可以从那里调试和构建。

    猜你喜欢
    • 2011-04-29
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多