前端老古董execCommand——操作 选中文本 样式

文章目录

    • ⭐前言
    • ⭐exe command api用法
      • 💖 example示例
      • 💖 测试效果
    • ⭐execommand和getSelection 的联系
    • ⭐总结
    • ⭐结束

yma16-logo

⭐前言

大家好,我是yma16,本文分享关于 前端老古董execCommand——操作选中文本。

execommand

当一个 HTML 文档切换到设计模式时,document暴露 execCommand 方法,该方法允许运行命令来操纵可编辑内容区域的元素。

大多数命令影响document的selection(粗体,斜体等),当其他命令插入新元素(添加链接)或影响整行(缩进)。
当使用contentEditable时,调用execCommand() 将影响当前活动的可编辑元素。

vue3系列相关文章:
vue3 + fastapi 实现选择目录所有文件自定义上传到服务器
前端vue2、vue3去掉url路由“ # ”号——nginx配置
csdn新星计划vue3+ts+antd赛道——利用inscode搭建vue3(ts)+antd前端模板
认识vite_vue3 初始化项目到打包
python_selenuim获取csdn新星赛道选手所在城市用echarts地图显示
让大模型分析csdn文章质量 —— 提取csdn博客评论在文心一言分析评论区内容
前端vue3——html2canvas给网站截图生成宣传海报
前端——html拖拽原理
前端 富文本编辑器原理——从javascript、html、css开始入门

⭐exe command api用法

execCommand 是一个 JavaScript 方法,用于执行编辑器中的命令,比如修改文本样式、插入链接、插入表格等操作。

语法

const bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

返回值
一个 Boolean ,如果是 false 则表示操作不被支持或未被启用。

参数

  • aCommandName
    一个 DOMString ,命令的名称。可用命令列表请参阅 命令 。
  • aShowDefaultUI
    一个 Boolean,是否展示用户界面,一般为 false。Mozilla 没有实现。
  • aValueArgument
    一些命令(例如 insertImage)需要额外的参数(insertImage 需要提供插入 image 的 url),默认为 null。

注意事项:
使用 execCommand 方法时,应该保证光标位于一个可编辑的区域,比如一个 contenteditable 属性为 true 的元素。
各个浏览器对于 execCommand 的支持情况不一样,不同的命令也有不同的兼容性,需要使用时要仔细检查浏览器兼容性。

💖 example示例

html部分

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="style.css" rel="stylesheet" type="text/css" />
    <title>InsCode execommand</title>
</head>

<body>
    <div class="container">
            <div class="container-box">
                <div class="container-box-header">
                    <div style="width:100%;text-align:left;margin:2px;">
                        execommand 指令 (选中内容修改)
                    </div>
                    <div class="container-box-header-button buttons" id="button-box-id">

                    </div>
                </div>
                <div style="width:100%;text-align:left;margin:2px;">
                    修改内容
                </div>
                <div class="container-box-header-content" contentEditable="true">
                    Every day of your life, it is important to take the time to “smell the roses” — to appreciate the
                    experiences that lead to happiness. This is part of being truly happy.
                    Happiness is a state of mind. It starts with accepting where you are, knowing where you are going
                    and planning to enjoy every moment along the way. You know how to be happy, and feel that you have
                    enough time or money or love or whatever you need to achieve your goals. And just feeling that you
                    have enough of everything means that you do indeed have enough.
                    You have to choose to be happy, and focus upon being happy, in order to be happy. If you instead
                    focus upon knowing that you will be happy if you achieve something, you will never be happy, as you
                    have not learned to “smell the roses”. The irony is that when you are happy, you are inevitably more
                    productive, and far more likely to achieve what everything-seekers are seeking.
                </div>
            </div>
        </div>



    </div>
    <script src="script.js"></script>
</body>

</html>

逻辑

var parms = [
    {
      cmd: "aCommandName",
      desc: "A DOMString representing the name of the command"
    },
    {
      cmd: "aShowDefaultUI",
      desc:
        "A Boolean indicating whether the default user interface should be shown. This is not implemented in Mozilla."
    },
    {
      cmd: "aValueArgument",
      desc:
        "A DOMString representing some commands (such as insertimage) require an extra value argument (the image's url). Pass an argument of null if no argument is needed."
    }
  ];
  var commands = [
    {
      cmd: "backColor",
      val: "red",
      desc:
        "Changes the document background color. In styleWithCss mode, it affects the background color of the containing block instead. This requires a color value string to be passed in as a value argument. (Internet Explorer uses this to set text background color.)"
    },
    {
      cmd: "bold",
      icon: "bold",
      desc:
        "Toggles bold on/off for the selection or at the insertion point. (Internet Explorer uses the STRONG tag instead of B.)"
    },
    {
      cmd: "contentReadOnly",
      desc:
        "Makes the content document either read-only or editable. This requires a boolean true/false to be passed in as a value argument. (Not supported by Internet Explorer.)"
    },
    {
      cmd: "copy",
      icon: "clipboard",
      desc:
        "Copies the current selection to the clipboard. Clipboard capability must be enabled in the user.js preference file. See"
    },
    {
      cmd: "createLink",
      val: "https://twitter.com/netsi1964",
      icon: "link",
      desc:
        "Creates an anchor link from the selection, only if there is a selection. This requires the HREF URI string to be passed in as a value argument. The URI must contain at least a single character, which may be a white space. (Internet Explorer will create a link with a null URI value.)"
    },
    {
      cmd: "cut",
      icon: "scissors",
      desc:
        "Cuts the current selection and copies it to the clipboard. Clipboard capability must be enabled in the user.js preference file. See"
    },
    {
      cmd: "decreaseFontSize",
      desc:
        "Adds a SMALL tag around the selection or at the insertion point. (Not supported by Internet Explorer.)"
    },
    {
      cmd: "delete",
      icon: "scissors",
      desc: "Deletes the current selection."
    },
    {
      cmd: "enableInlineTableEditing",
      desc:
        "Enables or disables the table row and column insertion and deletion controls. (Not supported by Internet Explorer.)"
    },
    {
      cmd: "enableObjectResizing",
      desc:
        "Enables or disables the resize handles on images and other resizable objects. (Not supported by Internet Explorer.)"
    },
    {
      cmd: "fontName",
      val: "'Inconsolata', monospace",
      desc:
        'Changes the font name for the selection or at the insertion point. This requires a font name string ("Arial" for example) to be passed in as a value argument.'
    },
    {
      cmd: "fontSize",
      val: "1-7",
      icon: "text-height",
      desc:
        "Changes the font size for the selection or at the insertion point. This requires an HTML font size (1-7) to be passed in as a value argument."
    },
    {
      cmd: "foreColor",
      val: "rgba(0,0,0,.5)",
      desc:
        "Changes a font color for the selection or at the insertion point. This requires a color value string to be passed in as a value argument."
    },
    {
      cmd: "formatBlock",
      val: "<blockquote>",
      desc:
        'Adds an HTML block-style tag around the line containing the current selection, replacing the block element containing the line if one exists (in Firefox, BLOCKQUOTE is the exception - it will wrap any containing block element). Requires a tag-name string to be passed in as a value argument. Virtually all block style tags can be used (eg. "H1", "P", "DL", "BLOCKQUOTE"). (Internet Explorer supports only heading tags H1 - H6, ADDRESS, and PRE, which must also include the tag delimiters &lt; &gt;, such as "&lt;H1&gt;".)'
    },
    {
      cmd: "forwardDelete",
      desc:
        "Deletes the character ahead of the cursor's position.  It is the same as hitting the delete key."
    },
    {
      cmd: "heading",
      val: "h3",
      icon: "header",
      desc:
        'Adds a heading tag around a selection or insertion point line. Requires the tag-name string to be passed in as a value argument (i.e. "H1", "H6"). (Not supported by Internet Explorer and Safari.)'
    },
    {
      cmd: "hiliteColor",
      val: "Orange",
      desc:
        "Changes the background color for the selection or at the insertion point. Requires a color value string to be passed in as a value argument. UseCSS must be turned on for this to function. (Not supported by Internet Explorer.)"
    },
    {
      cmd: "increaseFontSize",
      desc:
        "Adds a BIG tag around the selection or at the insertion point. (Not supported by Internet Explorer.)"
    },
    {
      cmd: "indent",
      icon: "indent",
      desc:
        "Indents the line containing the selection or insertion point. In Firefox, if the selection spans multiple lines at different levels of indentation, only the least indented lines in the selection will be indented."
    },
    {
      cmd: "insertBrOnReturn",
      desc:
        "Controls whether the Enter key inserts a br tag or splits the current block element into two. (Not supported by Internet Explorer.)"
    },
    {
      cmd: "insertHorizontalRule",
      desc:
        "Inserts a horizontal rule at the insertion point (deletes selection)."
    },
    {
      cmd: "insertHTML",
      val: "&lt;h3&gt;Life is great!&lt;/h3&gt;",
      icon: "code",
      desc:
        "Inserts an HTML string at the insertion point (deletes selection). Requires a valid HTML string to be passed in as a value argument. (Not supported by Internet Explorer.)"
    },
    {
      cmd: "insertImage",
      val: "http://dummyimage.com/160x90",
      icon: "picture-o",
      desc:
        "Inserts an image at the insertion point (deletes selection). Requires the image SRC URI string to be passed in as a value argument. The URI must contain at least a single character, which may be a white space. (Internet Explorer will create a link with a null URI value.)"
    },
    {
      cmd: "insertOrderedList",
      icon: "list-ol",
      desc:
        "Creates a numbered ordered list for the selection or at the insertion point."
    },
    {
      cmd: "insertUnorderedList",
      icon: "list-ul",
      desc:
        "Creates a bulleted unordered list for the selection or at the insertion point."
    },
    {
      cmd: "insertParagraph",
      icon: "paragraph",
      desc:
        "Inserts a paragraph around the selection or the current line. (Internet Explorer inserts a paragraph at the insertion point and deletes the selection.)"
    },
    {
      cmd: "insertText",
      val: new Date(),
      icon: "file-text-o",
      desc:
        "Inserts the given plain text at the insertion point (deletes selection)."
    },
    {
      cmd: "italic",
      icon: "italic",
      desc:
        "Toggles italics on/off for the selection or at the insertion point. (Internet Explorer uses the EM tag instead of I.)"
    },
    {
      cmd: "justifyCenter",
      icon: "align-center",
      desc: "Centers the selection or insertion point."
    },
    {
      cmd: "justifyFull",
      icon: "align-justify",
      desc: "Justifies the selection or insertion point."
    },
    {
      cmd: "justifyLeft",
      icon: "align-left",
      desc: "Justifies the selection or insertion point to the left."
    },
    {
      cmd: "justifyRight",
      icon: "align-right",
      desc: "Right-justifies the selection or the insertion point."
    },
    {
      cmd: "outdent",
      icon: "outdent",
      desc: "Outdents the line containing the selection or insertion point."
    },
    {
      cmd: "paste",
      icon: "clipboard",
      desc:
        "Pastes the clipboard contents at the insertion point (replaces current selection). Clipboard capability must be enabled in the user.js preference file. See"
    },
    {
      cmd: "redo",
      icon: "repeat",
      desc: "Redoes the previous undo command."
    },
    {
      cmd: "removeFormat",
      desc: "Removes all formatting from the current selection."
    },
    {
      cmd: "selectAll",
      desc: "Selects all of the content of the editable region."
    },
    {
      cmd: "strikeThrough",
      icon: "strikethrough",
      desc:
        "Toggles strikethrough on/off for the selection or at the insertion point."
    },
    {
      cmd: "subscript",
      icon: "subscript",
      desc:
        "Toggles subscript on/off for the selection or at the insertion point."
    },
    {
      cmd: "superscript",
      icon: "superscript",
      desc:
        "Toggles superscript on/off for the selection or at the insertion point."
    },
    {
      cmd: "underline",
      icon: "underline",
      desc:
        "Toggles underline on/off for the selection or at the insertion point."
    },
    {
      cmd: "undo",
      icon: "undo",
      desc: "Undoes the last executed command."
    },
    {
      cmd: "unlink",
      icon: "chain-broken",
      desc: "Removes the anchor tag from a selected anchor link."
    },
    {
      cmd: "useCSS ",
      desc:
        "Toggles the use of HTML tags or CSS for the generated markup. Requires a boolean true/false as a value argument. NOTE: This argument is logically backwards (i.e. use false to use CSS, true to use HTML). (Not supported by Internet Explorer.) This has been deprecated; use the styleWithCSS command instead."
    },
    {
      cmd: "styleWithCSS",
      desc:
        "Replaces the useCSS command; argument works as expected, i.e. true modifies/generates style attributes in markup, false generates formatting elements."
    }
  ];
  
  var commandRelation = {};
  
  function supported(cmd) {
    var css = !!document.queryCommandSupported(cmd.cmd)
      ? "btn-succes"
      : "btn-error";
    return css;
  }
  
  function icon(cmd) {
    return typeof cmd.icon !== "undefined" ? "fa fa-" + cmd.icon : "";
  }
  
  function doCommand(cmdKey) {
    var cmd = commandRelation[cmdKey];
    if (supported(cmd) === "btn-error") {
      alert("execCommand(“" + cmd.cmd + "”)\nis not supported in your browser");
      return;
    }
    val =
      typeof cmd.val !== "undefined"
        ? prompt("Value for " + cmd.cmd + "?", cmd.val)
        : "";
    document.execCommand(cmd.cmd, false, val || ""); // Thanks to https://codepen.io/bluestreak for finding this bug
  }
  
  function init() {
    var html = "",
      template =
        '<span><code class="btn btn-xs %btnClass%" title="%desc%" οnmοusedοwn="event.preventDefault();" οnclick="doCommand(\'%cmd%\')"><i class="%iconClass%"></i> %cmd%</code></span>';
    commands.map(function (command, i) {
      commandRelation[command.cmd] = command;
      var temp = template;
      temp = temp.replace(/%iconClass%/gi, icon(command));
      temp = temp.replace(/%desc%/gi, command.desc);
      temp = temp.replace(/%btnClass%/gi, supported(command));
      temp = temp.replace(/%cmd%/gi, command.cmd);
      html += temp;
    });
    console.log('html',html)
    document.getElementById("button-box-id").innerHTML = html;
  }
  
window.onload=()=>{
    init();
}
  

inscode案例

💖 测试效果

选中区域 加上 bold
bold
添加链接 https://blog.csdn.net/qq_38870145
link
添加效果
link-res

⭐execommand和getSelection 的联系

使用execommand的前提是存在getSelection 选区。

⭐总结

execCommand 在使用时要保持选区的状态,所以按钮事件配置关联需要阻止浏览器的点击行为(preventDefault)。
execCommand 的相关问题

  1. 回显选区文字的样式(需要实时获取选区内容)
  2. ie浏览器兼容性问题

兼容性方案:
execCommand 方法是一个过时的方法,它是用于在浏览器中执行命令的。该方法已经被废弃,不建议使用。

替代方案取决于你想要实现的功能。以下是几种可能的替代方案:

  1. 使用原生 JavaScript 方法:根据你想要实现的功能,可以使用原生 JavaScript 方法来替代 execCommand。例如,如果你想要插入文本,可以使用 document.execCommand(“insertText”, false, “Hello, World!”) 的替代方法:element.value += “Hello, World!”。

  2. 使用富文本编辑器库:如果你想要实现更复杂的文本编辑功能,可以考虑使用富文本编辑器库,例如 TinyMCE、Quill、CKEditor 等。这些库提供了丰富的 API 和功能,可以更方便地进行文本编辑操作。

  3. 使用内容编辑 API:一些网页编辑器提供了内容编辑 API,可以让你通过 API 直接修改编辑器的内容。例如,ContentEditable API 允许你直接修改一个元素的内容,而不需要使用 execCommand。

⭐结束

本文分享到这结束,如有错误或者不足之处欢迎指出!
moon

👍 点赞,是我创作的动力!
⭐️ 收藏,是我努力的方向!
✏️ 评论,是我进步的财富!
💖 感谢你的阅读!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/712961.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【Linux】进程_4

文章目录 五、进程4. 进程状态5. 进程优先级6. 进程的调度和转换 未完待续 五、进程 4. 进程状态 当进程属于挂起状态时&#xff0c;进程的可执行程序代码和数据均会被从内存中换入到磁盘中&#xff0c;此时进程的PCB并没有消失&#xff0c;只要操作系统还需要管理这个进程&a…

ChatGPT关联技术

ChatGPT关联技术 一、前馈神经网络二、序列到序列模型&#xff08;Seq2Seq&#xff09;三、自注意力机制四、多头自注意力机制五、自监督学习六、Transformer模型七、语言生成技术八、多语种语言模型九、预训练语言模型十、生成式预训练模型&#xff08;GPT&#xff09;十一、近…

【odoo】odoo.conf文件配置

概要 odoo.conf 文件是 Odoo 服务器的配置文件&#xff0c;它用于定义和管理 Odoo 运行时的各种参数。这个文件包含了许多配置选项&#xff0c;可以帮助管理员根据特定的需求和环境来调整 Odoo 服务器的行为。 主要功能 数据库连接设置&#xff1a;定义 Odoo 连接到 PostgreSQL…

使用tkinter创建带有图标的菜单栏

使用tkinter创建带有图标的菜单栏 效果代码代码解析创建主窗口加载图标创建菜单栏添加文件菜单添加带图标的菜单项 Tkinter 的默认菜单外观较为简单&#xff0c;可以通过自定义和添加图标&#xff0c;让菜单显示更好看。 效果 代码 import tkinter as tk from tkinter import …

【SpringBoot】SpringBoot:构建安全的Web应用程序

文章目录 引言为什么需要安全Spring Security概述配置Spring Security添加依赖基本配置 用户认证创建用户实体类创建用户存储库自定义用户服务更新安全配置 用户授权更新用户实体类更新自定义用户服务更新安全配置 防护措施防止SQL注入使用参数化查询 防止跨站脚本&#xff08;…

Java17 --- RabbitMQ之插件使用

目录 一、Federation插件 1.1、运行两个rabbitmq实例 1.2、启用插件 1.3、在下游端点添加上游端点 1.4、创建策略 1.6、测试 二、联邦队列 2.1、创建策略 2.2、创建交换机与队列 2.2.1、创建52000的队列与交换机 2.2.2、创建62000的队列 三、Shovel 3.1、启…

WNR最便捷美观的开源桌面计时器工具

华丽外观&#xff0c;功能全面。工作和休息的完美计时器。跨平台支持&#xff0c;无论是Windows、Mac还是Linux&#xff0c;WNR都能轻松驾驭。 超强全屏专注模式 对于寻找高效工作/休息管理工具却屡屡受挫的用户&#xff0c;WNR的“全屏专注模式”无疑是终极解决方案。它确保在…

Android 蓝牙配对Settings应用里面的简要流程记录

Android 蓝牙配对Settings应用里面的简要流程记录 文章目录 Android 蓝牙配对Settings应用里面的简要流程记录一、前言二、Settings蓝牙配对的关键代码1、接收蓝牙请求的地方 AndroidManifest.xml2、BluetoothPairingRequest3、BluetoothPairingService4、BluetoothPairingDial…

利用机器学习重构视频中的人脸

引言 中国与英国的研究团队携手合作&#xff0c;开创了一种创新的视频面孔重塑技术。这项技术能够以极高的一致性对视频中的面部结构进行逼真的放大和缩小&#xff0c;且避免了常见伪影的产生。 从研究人员选取的YouTube视频样例中可见&#xff0c;经过处理后&#xff0c;女演…

LC1020:飞地的数量

题目 给你一个大小为 m x n 的二进制矩阵 grid &#xff0c;其中 0 表示一个海洋单元格、1 表示一个陆地单元格。 一次 移动 是指从一个陆地单元格走到另一个相邻&#xff08;上、下、左、右&#xff09;的陆地单元格或跨过 grid 的边界。 返回网格中 无法 在任意次数的移动…

在ubuntu中启动docker的mysql8镜像

首先查看docker是否启动&#xff1a; docker ps #出现信息就是启动成功 启动命令&#xff1a; sudo systemctl start docker 设置开机自启&#xff1a; sudo systemctl enable docker 查询下载好的mysql8的镜像文件&#xff1a; docker images 在启动查询好的镜像文件&#…

Oracle--19C在Centos7上的静默安装(rpm版)

一、Oracle 19c Linux安装&#xff08;Centos 7&#xff09; 1.查看磁盘可用空间及配置ip地址 [rootlocalhost /]# df -h 文件系统 容量 已用 可用 已用% 挂载点 devtmpfs 1.4G 0 1.4G 0% /dev tmpfs 1.4G …

【Pytorch】一文向您详细介绍 model.eval() 的作用和用法

【Pytorch】一文向您详细介绍 model.eval() 的作用和用法 下滑查看解决方法 &#x1f308; 欢迎莅临我的个人主页 &#x1f448;这里是我静心耕耘深度学习领域、真诚分享知识与智慧的小天地&#xff01;&#x1f387; &#x1f393; 博主简介&#xff1a;985高校的普通本硕…

桂电人工智能学院大数据实验,使用 Docker 搭建 hadoop 集群

桂电人工智能学院大数据实验&#xff0c;使用 Docker 搭建 hadoop 集群 第一步 安装 Docker, Windows 上可以使用 Docker Desktop 下载地址&#xff1a;https://www.docker.com/products/docker-desktop/ 安装过程自行谷歌 安装好的标志&#xff1a;打开终端 运行docker p…

论文阅读:基于谱分析的全新早停策略

来自JMLR的一篇论文&#xff0c;https://www.jmlr.org/papers/volume24/21-1441/21-1441.pdf 这篇文章试图通过分析模型权重矩阵的频谱来解释模型&#xff0c;并在此基础上提出了一种用于早停的频谱标准。 1&#xff0c;分类难度对权重矩阵谱的影响 1.1 相关研究 在最近针对…

ERP、CRM、MRP、PLM、APS、MES、WMS、SRM系统介绍

一、ERP系统 ERP系统&#xff0c;即企业资源计划&#xff08;Enterprise Resource Planning&#xff09;系统&#xff0c;是一种集成管理软件系统&#xff0c;旨在帮助企业实现资源的有效管理和优化。以下是对ERP系统的详细介绍&#xff1a; 1、定义与功能 ERP是企业资源计划…

1832javaERP管理系统之车间计划管理Myeclipse开发mysql数据库servlet结构java编程计算机网页项目

一、源码特点 java erp管理系统之车间计划管理是一套完善的web设计系统&#xff0c;对理解JSP java编程开发语言有帮助采用了serlvet设计&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统采用web模式&#xff0c;系统主要采用B/S模式开发。开发环境为TOMCAT7.0,Mye…

PCIe总线-RK3588 PCIe子系统简介(八)

1.PCIe子系统 RK3588 PCIe子系统如下图所示。总共拥有5个PCIe控制器。PCIe30X4(4L)支持RC和EP模式&#xff0c;其他4个仅支持RC模式。ITS port 1连接PCIe30X4(4L)和PCIe30X2(2L)控制器&#xff0c;PCIe30X4(4L)和PCIe30X2(2L)控制器使用PCIe3.0 PIPE PHY。ITS port 0连接PCIe3…

【2024最新华为OD-C/D卷试题汇总】[支持在线评测] 游戏表演赛分队(100分) - 三语言AC题解(Python/Java/Cpp)

🍭 大家好这里是清隆学长 ,一枚热爱算法的程序员 ✨ 本系列打算持续跟新华为OD-C/D卷的三语言AC题解 💻 ACM银牌🥈| 多次AK大厂笔试 | 编程一对一辅导 👏 感谢大家的订阅➕ 和 喜欢💗 📎在线评测链接 游戏表演赛分队(100分) 🌍 评测功能需要订阅专栏后私信联系…

uniapp使用css实现瀑布流

页面 <template><view><gj v-if"likeList.length 0"></gj><view v-else class"list"><view class"pbl" v-for"(item,index) in likeList" :key"index"><view class"image&quo…