如何使用单击事件双击时模拟突出显示文本



我想在双击文本时模拟所选文本上的突出显示操作,但只需单击一个单击事件。我该怎么做?我尝试使用这些代码但失败了

handleOnClick(event) {
event.preventDefault();
//i thought this suppose to trigger double click event 
//and highlight the text under the mouse cursor
event.target.dispatchEvent(new MouseEvent('dblclick', {bubbles:true}));
//...
}

你需要整个div 元素还是只是其中的一部分? 这是一个在双击事件中突出显示整个div 的解决方案。

HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Highlight</title>
</head>
<body>
<div id="text">Text to be highlighted</div>
</body>
</html>
CSS
.highlight {
background: yellow;
}
JS
document.querySelector('#text')
.addEventListener('dblclick', () => {
document.querySelector('#text').classList.add('highlight');
});