调用文档时。getSelection,生成的选择对象似乎返回 Firefox 中的前一个节点(查看 anchorNode 和 anchorOffset)
在 Safari/Edge 中选择(通过例如双击)“BBBBBBB”,然后单击按钮将在控制台中显示“BBBBBBB”和 anchorOffset 0,而在 Firefox 中它将显示“AAAAAAAA”和 9。我希望 Safari/Edge 的行为。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>
anchor node != selected node
</title>
<script>
window.addEventListener("DOMContentLoaded", () => {
let input = document.getElementById("b");
input.addEventListener("click", ()=> {
let selection = document.getSelection();
if(selection) {
console.log(selection.anchorNode.textContent + " " + selection.anchorOffset);
}
});
});
</script>
</head>
<body>
<span>AAAAAAAA </span><span>BBBBBBB </span><span>CCCCCCC </span>
<input id="b" type="button" value="click me">
</body>
</html>