首页 > 解决方案 > 文本选择功能的实现无法正常工作

问题描述

我在选择时突出显示文本有一个很大的问题,我可以使用onMouseUp事件和浏览器 API选择测试window.getSelection().getRangeAt(0)我得到了
我突出显示的文本的坐标并且它被正确突出显示,为此我使用以下实现。

const {useState}=React;

function App() {
  const [text, setText] = useState('Some text will be here but this one will be yellow'),
        [start, setStart] = useState(0),
        [end, setEnd] = useState(0)

  const onMouseUp = ()=> {
    let data = window.getSelection().getRangeAt(0)
    setStart(data.startOffset)
    setEnd(data.endOffset)
  }

  return (
    <div className='App'>
      <div className='textContent'>
          {text.slice(0, start)}
          <span className="selected">{text.slice(start, end)}</span>
          {text.slice(end)}
      </div> 
      
      <div className='textContent' onMouseUp={onMouseUp}>
          {text}
      </div> 
    </div>
  )
}



const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
.selected{
  background: #f00;
}

.App{
  position: relative;
}

.textContent{
  position: absolute;
  top: 0;
  left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

<div id="root"></div>

我的代码在代码沙盒中运行良好,但是当我启动 create-react-app 应用程序时,它运行不正确,并且在 dbl 单击和另一个操作之后,我看到不正确的选择等等,为什么会发生这种情况?

这是codesandbox的链接

标签: javascriptcreate-react-app

解决方案


问题在于更新 chrome 浏览器,更新通过后,显然 chrome 社区因此加快了用户的更新)


推荐阅读