首页 > 解决方案 > 如何确定用户选择范围

问题描述

我目前正在开发一个由不同面板和区域组成的 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/Selectionhttps://w3c.github.io/selection-api/

我尝试stopPropagation()在 dragstart-events 上使用,但这似乎没有任何效果。

标签: javascripthtml

解决方案


您可以使用阻止默认选择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>


推荐阅读