gpt4 book ai didi

javascript - 用 JavaScript 模仿 Ctrl+A

转载 作者:数据小太阳 更新时间:2023-10-29 05:35:04 26 4
gpt4 key购买 nike

我想以编程方式选择页面上的所有文本,结果与按组合键 Ctrl+A 完全相同.

使用document.getSelection().selectAllChildren(body)的问题是选择还将包括用户无法选择的文本节点,即 <script> </script>或有 user-select:none 的节点在 CSS 中定义:

<div style="-moz-user-select:none">必选</div>

有方法 modify在可以像这样使用的选择对象上: selection.modify("extend", "forward", "documentboundary");将选择从文档的开头扩展到结尾,这将忽略任何脚本或样式元素内容以及带有 -moz-user-select:none 的元素- 不幸的是 Firefox 不允许 documentboundary作为 3. 参数和 word帮助不大。

有没有快速的方法来完成这个?只需要在 Firefox 中工作。

编辑(不太好的解决方案): 选择第一个文本节点,然后使用 selection.modify('extend', 'forward', 'line')反复selection.focusNode不等于最后一个文本节点 - 但根据文档的长度,这可能需要几秒钟!

编辑: selection.selectAllChildren将在 Chrome 中按预期工作,其中带有 user-select:none 的文本元素不会被选中 - 不幸的是在 FF 中有不同的行为。

编辑:这不是 this post 的副本因为我既没有解决 contenteditable元素,我也不关心它们;)

最佳答案

在我看来,最有效的方法是将您想要选择的内容移动到它自己的可选 div 中,然后选择其中的 AllChildren。我在谷歌搜索、几个堆栈溢出问题和一些随机站点上尝试了这个。在每种情况下,结果都是即时的,并且完全相同的是 ctrl+A

function selectAll() {
var sel = window.getSelection();
var body = document.querySelector("body");
// Place the children in an array so that we can use the filter method
var children = Array.prototype.slice.call(body.children);

// Create the selectable div
var selectable = document.createElement("div");

// Style the selectable div so that it doesn't break the flow of a website.

selectable.style.width = '100%';
selectable.style.height = '100%';
selectable.margin = 0;
selectable.padding = 0;
selectable.position = 'absolute';

// Add the selectable element to the body
body.appendChild(selectable);

// Filter the children so that we only move what we want to select.
children = children.filter(function(e) {
var s = getComputedStyle(e);
return s.getPropertyValue('user-select') != 'none' && e.tagName != 'SCRIPT'
});
// Add each child to the selectable div
for (var i = 0; i < children.length; i++) {
selectable.appendChild(children[i]);
}

// Select the children of the selectable div
sel.selectAllChildren(selectable);

}

selectAll();

关于javascript - 用 JavaScript 模仿 Ctrl+A,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44028502/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com