js execCommand()

  • Post author:
  • Post category:其他


第一次接触execCommand()是在项目中一个需要复制一个随机数的时候,查询了一下发现了document的这个方法,使用方式如下



html

<input readonly="readonly"  class="copyNum text-input" type="text"/>
<button class="copyBtn">复制</button>



主要js

$('.copyBtn').click(function () {
    $('.copyNum').select();    //选中要复制内容的输入框
    document.execCommand("copy",false,null);
})

这样就可以实现点击复制按钮,复制input框中的代码。

而后我去查询了execCommand的用法:

document.execCommand(commandName, showDefaultUI, valueArgument)


返回值:

Boolean类型,正常操作返回true,若返回值位false则说明操作不被支持或者未被启用(execCommand有很多操作)


参数




commandName:一个字符串代表命令的名称(copy、Bold等)

showDefaultUI:一个boll类型,是否展示用户界面

valueArgument:额外的参数,比如设置背景色的时候的颜色等


常见命令:

1. copy

拷贝当前选中内容到剪贴板。

document.execCommand("copy",false,null);

2. selectAll 选中编辑区里面的全部内容

document.execCommand("selectAll");

3. Bold 将选中的内容加粗

document.execCommand("Bold");    //需要在designMode模式下,document.designMode = 'On';打开这个模式
4. hiliteColor
document.execCommand("hiliteColor",true,'yellow');    //同需要在dedsignMode模式下,还需设置document.contentEditable = true;

5. fontSize

document.execCommand("fontSize",true,10);

还有许多的命令,但是使用时一定要注意条件,像copy就在一般模式下就可以使用的,有些呢需要在设计模式下才能使用等等,详细请参考

点击打开链接



版权声明:本文为qq_33201818原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。