2 回答

TA貢獻1833條經驗 獲得超4個贊

TA貢獻1828條經驗 獲得超3個贊
默認行為取決于瀏覽器,因此您需要進行一些檢查才能給出一致的結果。
這是一個簡單的示例,它將event.target
元素與parentElement
返回的文本節點的進行比較selection.focusNode
,如果不匹配,它會檢查焦點節點的兄弟節點是否匹配并相應地調整偏移量。
您需要使其更加穩健。您還需要處理方向性(從左到右選擇會產生反向焦點,并且選擇從右到左的錨節點)。您也可以看看Selection.containsNode()
function handleSelection(e) {
? const selection = window.getSelection();
??
? const fNode = selection.focusNode;
??
? const fElement = fNode.parentElement;
? const tElement = e.target;
??
? let word_index = tElement.dataset.index;
? let char_index = selection.focusOffset;
??
? if (!fElement.isEqualNode(tElement)?
? ? && fElement.nextElementSibling.isEqualNode(tElement)) {
? ? char_index=0;
? }
??
? console.log(
? ? 'fNode: ', fNode.parentElement.innerText,
? ? ' tNode: ', tElement.innerText,
? ? ' char: ', char_index,
? ? ' word: ', word_index
? );
}
const words = document.querySelectorAll('.word');
words.forEach((w, i) => (
? w.dataset.index = i+1,?
? w.addEventListener('click', handleSelection)));
.word {
? border: 1px solid gray;
? font-size: 2rem;
}
<p class="sentence">
? <span class="word">Hello </span><span class="word">wonderful</span><span class="word"> world.</span>
</p>
添加回答
舉報