@@ -871,6 +871,8 @@ while(treeWalker.nextNode()) {
871871
872872### document.execCommand(),document.queryCommandSupported(),document.queryCommandEnabled()
873873
874+ ** (1)document.execCommand()**
875+
874876如果` document.designMode ` 属性设为` on ` ,那么整个文档用户可编辑;如果元素的` contenteditable ` 属性设为` true ` ,那么该元素可编辑。这两种情况下,可以使用` document.execCommand() ` 方法,改变内容的样式,比如` document.execCommand('bold') ` 会使得字体加粗。
875877
876878``` javascript
@@ -899,24 +901,54 @@ if (url) {
899901
900902` document.execCommand() ` 方法可以执行的样式改变有很多种,下面是其中的一些:bold、insertLineBreak、selectAll、createLink、insertOrderedList、subscript、delete、insertUnorderedList、superscript、formatBlock、insertParagraph、undo、forwardDelete、insertText、unlink、insertImage、italic、unselect、insertHTML、redo。这些值都可以用作第一个参数,它们的含义不难从字面上看出来。
901903
902- ` document.queryCommandEnabled() ` 方法返回一个布尔值,表示浏览器是否允许使用这个方法。
904+ ** (2)document.queryCommandSupported()**
905+
906+ ` document.queryCommandSupported() ` 方法返回一个布尔值,表示浏览器是否支持` document.execCommand() ` 的某个命令。
903907
904908``` javascript
905- if (document .queryCommandEnabled (' SelectAll' )) {
906- // ...
909+ if (document .queryCommandSupported (' SelectAll' )) {
910+ console . log ( ' 浏览器支持选中可编辑区域的所有内容 ' );
907911}
908912```
909913
910- ` document.queryCommandSupported() ` 方法返回一个布尔值,表示当前是否可用某种样式改变。比如,加粗只有存在文本选中时才可用,如果没有选中文本,就不可用。
914+ ** (3)document.queryCommandEnabled()**
915+
916+ ` document.queryCommandEnabled() ` 方法返回一个布尔值,表示当前是否可用某种样式改变。比如,加粗只有存在文本选中时才可用,如果没有选中文本,就不可用。
911917
912918``` javascript
913- if (document .queryCommandSupported (' SelectAll' )) {
914- // ...
919+ // HTML 代码为
920+ // <input type="button" value="Copy" onclick="doCopy()">
921+
922+ function doCopy (){
923+ // 浏览器是否支持 copy 命令
924+ if (document .queryCommandSupported (' copy' )) {
925+ copyText (' 你好' );
926+ }else {
927+ console .log (' 浏览器不支持' );
928+ }
929+ }
930+
931+ function copyText (text ) {
932+ var input = document .createElement (' textarea' );
933+ document .body .appendChild (input);
934+ input .value = text;
935+ input .focus ();
936+ input .select ();
937+
938+ // 当前是否有选中文字
939+ if (document .queryCommandEnabled (' copy' )) {
940+ var success = document .execCommand (' copy' );
941+ input .remove ();
942+ console .log (' Copy Ok' );
943+ } else {
944+ console .log (' queryCommandEnabled is false' );
945+ }
915946}
916947```
917948
918- ` document.queryCommandEnabled() ` 方法返回一个布尔值,
949+ 上面代码中,先判断浏览器是否支持 ` copy ` 命令(允许选中可编辑区域的内容,将其复制到剪贴板),如果支持,就新建一个临时编辑框,里面写入内容“你好”,并将其选中。然后,判断是否选中成功,如果成功,就将“你好”复制到剪贴板,再删除那个临时编辑框。
919950
920951### document.getSelection()
921952
922953这个方法指向` window.getSelection() ` ,参见` window ` 对象一节的介绍。
954+
0 commit comments