【问题标题】:Unable to add 2nd selection range (Google Chrome)无法添加第二个选择范围(谷歌浏览器)
【发布时间】:2020-09-09 18:11:36
【问题描述】:

我正在尝试以编程方式在 Chrome 中添加多个选择区域。

从这里:Can you set and/or change the user’s text selection in JavaScript?

我发现这个函数用于在 SO 上选择元素文本(我添加了 clearFirst 参数):

function selectElementContents(el, clearFirst) {
    if (window.getSelection && document.createRange) {
//        console.log('here');
        var sel = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(el);
        if (clearFirst) sel.removeAllRanges();
        sel.addRange(range);
    } else if (document.selection && document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.select();
    }
}

然后尝试这样称呼它:

  var table = document.createElement("table");
  document.body.appendChild(table);
  for (var i = 0; i < 3; i++) {
    let row = table.insertRow();
    for (var j = 0; j < 3; j++) {
       let cell = row.insertCell();
       cell.innerText = "" + i + "," + j;
    }
  }
  $(table).on("click", function() {
    let tds = $(this).find("td");
    console.log("td: " + tds.get(0));
    selectElementContents(tds.get(0), true);
    selectElementContents(tds.get(3), false);

  });

第一个 TD 的选择工作正常,但没有选择第二个范围。我确认selectElementContents 正在通过“真实”代码(注释掉的console.log 所在的位置)。是不允许在 Chrome 中添加多个选择范围,还是我没有正确执行此操作?

【问题讨论】:

    标签: javascript jquery google-chrome selection


    【解决方案1】:

    答案似乎包含在 Chrome 扩展程序中:“多行文本选择”https://chrome.google.com/webstore/detail/multiline-text-selection/ajbomhojbckleofgngogoecoaefclnol?hl=en

    因此,在默认 chrome 中,不支持多个选择范围。但是这个扩展可以启用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-15
      • 2015-08-26
      • 1970-01-01
      相关资源
      最近更新 更多