javascript - 如何确定用户选择范围
问题描述
我目前正在开发一个由不同面板和区域组成的 Web 应用程序。一个面板包含一个巨大的表格,另一个面板包含一个描述框,等等。
通常,用户可以拖动鼠标并选择 html 页面内的任何文本范围。我希望用户只能选择一个面板内的文本或最多一个障碍。
例如,当表格处于焦点时,通过鼠标选择文本或按 Ctrl-A 应该只选择其中的文本。并非页面上的每个可选文本。
<div id="application">
<p>Not this text</p>
<div id="another-panel">Nor that</div>
<div id="special-panel-including-big-table">
Hitting Ctrl-A here should only select THIS text
</div>
</div>
我需要以某种方式在父元素(如表格面板)上定义一个障碍,以防止将选择进一步扩展到 DOM 树。
我咨询了https://developer.mozilla.org/en-US/docs/Web/API/Selection和 https://w3c.github.io/selection-api/
我尝试stopPropagation()
在 dragstart-events 上使用,但这似乎没有任何效果。
解决方案
您可以使用阻止默认选择e.preventDefault()
并创建您自己的选择。
如果您的表格包含可以获得焦点的输入元素,您可以为此进行额外检查。这不包括在我的示例中。
document.addEventListener('keydown', (e) => {
if(e.ctrlKey && e.key === 'a') {
//Prevent the default select all
e.preventDefault();
//Select only the contents of div#special-panel-including-big-table
var targetEl = document.getElementById('special-panel-including-big-table');
var range;
if (window.getSelection && document.createRange) {
var selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(targetEl);
selection.removeAllRanges();
selection.addRange(range);
}
}
});
<div id="application">
<p>Not this text</p>
<div id="another-panel">Nor that</div>
<div id="special-panel-including-big-table">
Hitting Ctrl-A here should only select THIS text
</div>
</div>
推荐阅读
- excel - 当有多个数据表时,如何使用 VBA 更新所选 Excel 数据表中的记录
- sql - 更新表语句 - 违反主键约束
- sql - 在加入 SQL Netezza 时使用窗口聚合函数
- vuejs2 - 不受欢迎的观察者执行顺序
- apache-kafka - Kafka 在某些主题上有 100% 的低复制分区
- html - 我希望显示类型网格内的图像在用作背景时显示为封面,但在我的情况下它是垂直挤压的
- android - 房间数据库在加载聊天时获取最后的聊天消息
- python - 无法添加 BinarySubTree
- flutter - ListView 与最喜欢的项目
- python - 如何将两个字典与里面的列表进行比较?