我注意到互聯網上有不同的解決方案,其中描述了如何檢測word用戶點擊的位置。但是我想知道是否有解決方案可以從單詞或用戶單擊的位置檢測字母。前任:
<div>this is the text</div>
當用戶點擊控制臺中的第一個字母時應該輸出t。
是否有一種解決方案可以像我上面描述的那樣使用 javascript 找到被點擊的字母?
uj5u.com熱心網友回復:
您可能可以使用Selection API來檢查游標的位置并提取最接近它的字母:
document.onclick = (evt) => {
const sel = getSelection();
if (sel.rangeCount) {
const range = sel.getRangeAt(0);
const targetedNode = range.startContainer;
const clickedLetter = targetedNode.textContent.substr(range.startOffset, 1);
console.log(clickedLetter);
}
};
<div>this is the text</div>
但是在很多極端情況下它很可能會失敗。
uj5u.com熱心網友回復:
使用Selection.focusOffset得到字符的位置,這是最接近游標點擊的焦點。
document.onclick = (event) => {
const selection = getSelection();
const charClicked = selection.focusNode.data[selection.focusOffset]
if (charClicked) {
console.log(charClicked);
}
};
<div>this is the text</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/339798.html
標籤:javascript
上一篇:如何從嵌套陣列中僅獲取布林值
