我在选择时突出显示文本时遇到了巨大问题,我可以使用onMouseUp
事件和浏览器APIwindow.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>
我的代码在codesandbox中运行得很好,但当我开始创建react应用程序时,它运行不正确,在dbl单击和另一个操作之后,我看到选择不正确等等,为什么会发生这种情况?
这是代码沙盒的链接
问题是在更新chrome浏览器时,在更新通过后,显然chrome社区因此加快了用户的更新(