javascript - 选择 API 和范围 API 有什么区别?
问题描述
我想知道选择 API 和范围 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();
}
问题
Selection API 和 Range 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>
解决方案
这一行解释了一切:
const range = selection.getRangeAt(0);
选择可以有多个范围。范围可能重叠。因此 - range 是具有自己 API 的选择的一部分。
推荐阅读
- c++ - 如何将 3d 维度不是固定大小的 3D 数组展平为 1D 数组?
- javascript - Promise.all() 与等待
- html - 如何悬停 HTML 相同的 ID 不同的类?
- c - 为什么我的命令行参数可以采用“2x”,尽管我设定了它只能采用整数的条件
- r - R Shiny,变异替换,如何变异从数据框中的 selectInput 中选择的特定列?
- php - 为什么我的 @foreach 语句在 Laravel 中不起作用?
- react-native - 本机基础更改按钮填充
- bash - 使用嵌套管道命令编写 bash 条件
- css - 浏览器不会为 div 元素选择 css,除非我在它之前放入一个假 css
- reactjs - 在我的 ReactApp 中使用 FakeJSON 返回“错误 - 缺少令牌”