无法添加第二个选择范围 (Google Chrome)
Unable to add 2nd selection range (Google Chrome)
我正在尝试以编程方式在 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
正在执行 "true" 代码(注释掉的 console.log 是)。在 Chrome 中添加多个选择范围是不允许的,还是我没有正确执行此操作?
答案似乎包含在 Chrome 扩展中:"Multiline Text Selection" https://chrome.google.com/webstore/detail/multiline-text-selection/ajbomhojbckleofgngogoecoaefclnol?hl=en
所以在默认情况下 chrome,不支持多选范围。但是这个扩展可以启用它。
我正在尝试以编程方式在 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
正在执行 "true" 代码(注释掉的 console.log 是)。在 Chrome 中添加多个选择范围是不允许的,还是我没有正确执行此操作?
答案似乎包含在 Chrome 扩展中:"Multiline Text Selection" https://chrome.google.com/webstore/detail/multiline-text-selection/ajbomhojbckleofgngogoecoaefclnol?hl=en
所以在默认情况下 chrome,不支持多选范围。但是这个扩展可以启用它。