当前位置:网站首页>富文本实现插值
富文本实现插值
2022-07-01 09:20:00 【tianming2018】
最近项目上需要一个富文本框实现插值操作,插值不可编辑,但是可以删除,尝试了好几种方案,最终决定用contenteditable这个属性来实现
首先, contenteditable="true"可以使元素成为可编辑状态
<div contenteditable="true"></div>
在设置了contenteditable属性的元素中,可以插入或编辑任意的元素,如果要实现不可编辑的插值的话,可以将插值的元素设置为contenteditable="false",这样,就实现了富文本插值。
但是,还有问题,如何将元素插入指定的光标位置
浏览器提供了selection和range对象来操作光标
// 将内容插入到光标位置,并将光标移动到内容元素末尾
function insertAtCursor(domNode) {
// 获取被选中的内容,起点和终点在同一位置为光标,不同位置为选区
const selection = window.getSelection();
// 被选中/focus的元素
const anchorNode = selection.anchorNode;
if (!anchorNode) return;
// 父节点
const range = selection.getRangeAt(0);
// 插入传入的元素节点
range.insertNode(domNode);
// collapse为true使起点和终点位于同一位置,即光标
// false时则为选区内容
range.collapse(true);
// 光标移到最后
const r = document.createRange();
r.selectNodeContents(domNode);
r.collapse(false);
const s = window.getSelection();
s.removeAllRanges();
s.addRange(r);
}
这样,就可以把元素插入光标位置,并把光标移动到元素末尾
边栏推荐
- Structure de l'arbre - - - arbre binaire 2 traversée non récursive
- [pytorch learning] torch device
- 【ESP 保姆级教程 预告】疯狂Node.js服务器篇 ——案例:ESP8266 + DS18B20温度传感器 +NodeJs本地服务+ MySQL数据库
- JS variable lifting
- Win7 pyinstaller reports an error DLL load failed while importing after packaging exe_ Socket: parameter error
- Pain points and solutions of equipment management in large factories
- delete和delete[]引发的问题
- Record a redis timeout
- An overview of the design of royalties and service fees of mainstream NFT market platforms
- Nacos service configuration and persistence configuration
猜你喜欢

dsPIC30F6014a LCD 方块显示

I use flask to write the website "one"

Mise en œuvre simple de l'équilibrage de la charge par nacos

Jetson Nano 安装TensorFlow GPU及问题解决

FAQ | FAQ for building applications for large screen devices

How to launch circle of friends marketing and wechat group activities

2.3 【kaggle数据集 - dog breed 举例】数据预处理、重写Dataset、DataLoader读取数据

2.4 激活函数

Structure de l'arbre - - - arbre binaire 2 traversée non récursive

2.2 【pytorch】torchvision. transforms
随机推荐
Leetcode daily question brushing record --540 A single element in an ordered array
[ESP nanny level tutorial] crazy completion chapter - Case: gy906 infrared temperature measurement access card swiping system based on the Internet of things
美团2022年机试
Preparing for the Blue Bridge Cup -- bit operation
MySQL optimization
js this丢失问题分析 及 解决方案
Shell script echo command escape character
Reproduced Xray - cve-2017-7921 (unauthorized access by Hikvision)
【pytorch】softmax函数
js函数arguments对象
Mysql 优化
MapReduce编程基础
Mise en œuvre simple de l'équilibrage de la charge par nacos
How to launch circle of friends marketing and wechat group activities
【ESP 保姆级教程】疯狂毕设篇 —— 案例:基于物联网的GY906红外测温门禁刷卡系统
利用闭包实现私有变量
Youqitong PE toolbox [vip] v3.7.2022.0106 official January 22 Edition
Shell script - special variables: shell $, $*, [email protected], $$$
SDN_ Simple summary
JS rewrite their own functions