我想知道选择API和Range API之间的主要目的有什么不同。
从下面的片段中,我们可以看到它们之间有某种程度的相互联系。当您设置一个属性时,您将自动设置另一个属性。甚至他们的一些方法也非常相似。
// Select text from 0-5 using the Selection API
function onClick1() {
root.focus();
const selection = window.getSelection();
selection.setBaseAndExtent(root.childNodes[0],0,root.childNodes[0],5);
getSelectionInfo();
}// Select text from 7 to 9 using the Range API
function onClick2() {
root.focus();
const selection = window.getSelection();
const range = selection.getRangeAt(0);
range.setStart(root.childNodes[0],6);
range.setEnd(root.childNodes[0],9);
getSelectionInfo();
}问题
选择API和范围API的主要区别是什么?
const root = document.getElementById('root');
const infoP = document.getElementById('info');
function onClick1() {
root.focus();
const selection = window.getSelection();
selection.setBaseAndExtent(root.childNodes[0],0,root.childNodes[0],5);
getSelectionInfo();
}
function reset() {
const selection = window.getSelection();
selection.removeAllRanges();
infoP.innerHTML = '';
}
function onClick2() {
root.focus();
const selection = window.getSelection();
const range = selection.getRangeAt(0);
range.setStart(root.childNodes[0],6);
range.setEnd(root.childNodes[0],9);
getSelectionInfo();
}
function getSelectionInfo() {
const selection = window.getSelection();
const range = selection.getRangeAt(0);
const text = `
<b>selection.anchorNode:</b> ${selection.anchorNode}
<b>selection.anchorOffset:</b> ${selection.anchorOffset}
<b>selection.focusNode:</b> ${selection.focusNode}
<b>selection.focusOffset:</b> ${selection.focusOffset}
<b>selection.isCollapsed:</b> ${selection.isCollapsed}
<b>selection.rangeCount:</b> ${selection.rangeCount}
<b>selection.type:</b> ${selection.type}\n
<b>range.collapsed:</b> ${range.collapsed}
<b>range.commonAncestorContainer:</b> ${range.commonAncestorContainer}
<b>range.startContainer:</b> ${range.startContainer}
<b>range.startOffset:</b> ${range.startOffset}
<b>range.endContainer:</b> ${range.endContainer}
<b>range.endOffset:</b> ${range.endOffset}
`;
infoP.innerHTML = text;
}#root {
border: 1px dotted blue;
}
#info {
white-space: pre-wrap;
}<div id="root" contenteditable>123456789</div>
<button onClick="onClick1()">Set Focus and Select 1-5 via Selection</button>
<button onClick="reset()">Reset</button>
<button onClick="onClick2()">Set Focus and Select 7-9 via Range</button>
<p><b>Selection info:</b></p>
<p id="info"></p>
发布于 2019-04-23 14:13:42
这一行解释了这一切:
const range = selection.getRangeAt(0);
选择可以有几个范围。范围可能重叠。因此,范围是使用它自己的API选择的一部分。
发布于 2021-06-11 00:02:15
由用户输入创建的非空选择始终包含单个范围--选择中的范围表示屏幕上所选择的内容。但是,您也可以以编程的方式创建与屏幕上显示的内容无关的范围。
这意味着您可以有多个范围,但您将只有一个选择(Firefox是例外,是唯一支持多个选择的主要浏览器)。
与选择不同,范围也没有方向。通过选择,锚点(选择开始的位置)可以出现在焦点之前或之后(选择结束的位置),这取决于用户选择的方向(从左到右/从上到下或从右到左/从下到顶)。但幅度不考虑方向。
https://stackoverflow.com/questions/55807900
复制相似问题