用JavaScript模拟Ctrl+A [英] Mimic Ctrl+A with JavaScript

查看:27
本文介绍了用JavaScript模拟Ctrl+A的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

使用document.getSelection().selectAllChildren(body)的问题在于,选择还将包括用户不可选择的文本节点,即<script> </script>或在css:

中定义了user-select:none的节点

<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元素,也不关心它们;)

推荐答案

在我看来,最有效的方法是将您想要选择的内容移动到它自己的可选目录中,然后选择该目录的所有子项。我在谷歌搜索、几个堆栈溢出问题和几个随机站点上尝试了这一方法。在每种情况下,结果都是瞬时的,并且完全相同的结果是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模拟Ctrl+A的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆