当前位置:网站首页>Add a string at the input and textarea cursors
Add a string at the input and textarea cursors
2022-06-25 14:24:00 【Fat goose 68】
List of articles
One 、 Reference resources
Two 、 Problem description
Business needs : The camera head has been illegally parked , You need to send a message to the relevant car owners
Development tasks : Relevant SMS templates need to be edited in advance , Such as time 、 license plate number 、 General template information such as the owner's name , You need to use specific characters instead of , Convenient background parsing . These strings are developed , It actually has no practical significance for those who write SMS templates
3、 ... and 、 Quick start
<html>
<head> </head>
<script type="text/javascript"> function add(str) {
var tc = document.getElementById("mytextarea"); var tclen = tc.value.length; tc.focus(); // Compatibility check if (typeof document.selection != "undefined") {
document.selection.createRange().text = str; } else {
tc.value = // Get the starting position of the cursor tc.value.substr(0, tc.selectionStart) + str + tc.value.substring(tc.selectionStart, tclen); } } </script>
<body>
<textarea rows="5" name="s1" cols="27" id="mytextarea">
Aim by clicking the button on the page button stay textarea Insert text where the cursor stays in the </textarea >
<ul>
<li>
<button onclick="add('huangbiao')"> Add the specified string </button>
</li>
</ul>
</body>
</html>
Four 、 Introduction to built-in objects
HTMLInputElement Introduce
attribute
- selectionStart
The position index of the first character selected , from 0 Start. If this value is greater than the element's value The length is also large , Will be regarded as value The index of the last position . - selectionEnd
Of the last character selected next Location index. If this value is greater than the element's value The length is also large , Will be regarded as value The index of the last position . - selectionDirection Optional
A string representing the selection direction, The possible values are : “forward” 、 “backward”、 “none” The default value is , Indicates that the direction is unknown or irrelevant .
- selectionStart
Selection Introduce
Concept
Selection Object represents the user selected text range or the current location of the caret . It represents the text selection in the page , It can span multiple elements .
Text selection is generated by the user dragging the mouse through the text .To get... For checking or modifying Selection object , Please call window.getSelection().
One Selection Object represents the... Selected by the user Range Set . Usually , It contains only one areavar selObj = window.getSelection(); var range = selObj.getRangeAt(0);selectionchange event
<!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" />
<title>Document</title>
</head>
<body>
<div>
Enter and select text here:<br /><input id="mytext" rows="2" cols="20" />
</div>
<div>selectionStart: <span id="start"></span></div>
<div>selectionEnd: <span id="end"></span></div>
<div>selectionDirection: <span id="direction"></span></div>
</body>
<script> const myinput = document.getElementById("mytext"); // myinput.addEventListener("selectionchange", () => { This is not valid document.addEventListener("selectionchange", () => {
// Only HTMLInputElement Nodes have selectionStart selectionEnd selectionDirection attribute document.getElementById("start").textContent = myinput.selectionStart; document.getElementById("end").textContent = myinput.selectionEnd; document.getElementById("direction").textContent = myinput.selectionDirection; }); </script>
</html>
Range
Concept
Range Interface represents a document fragment that contains a part of a node and a text node .
A scope is a continuous part of a document . A range includes the entire node , It can also contain part of the node , For example, part of a text node . Usually, users can only select one range , But sometimes users may choose multiple ranges .
It can be used Document Object's Document.createRange Method creation Range, It can also be used. Selection Object's getRangeAt Method to get Range. in addition , You can also use Document Object's constructor Range() To get Range.
5、 ... and 、 Code set
Add... At the cursor position of the text control character string
<html>
<head> </head>
<script type="text/javascript"> function add(str) {
var tc = document.getElementById("mytextarea"); var tclen = tc.value.length; tc.focus(); if (typeof document.selection != "undefined") {
document.selection.createRange().text = str; } else {
tc.value = // Get the starting position of the cursor tc.value.substr(0, tc.selectionStart) + str + tc.value.substring(tc.selectionStart, tclen); } } function selectAll() {
var tc = document.getElementById("mytextarea"); // textarea Select all contents tc.select(); // Focus selected tc.focus(); } function selectPos() {
var start = 5, end = 10; var tc = document.getElementById("mytextarea"); // Not selected , The default is all from 0 Start console.log(tc.selectionStart); // No area selected , And selectionStart In the same place console.log(tc.selectionEnd); // Set the selected area , The selected content will not be highlighted in the browser tc.setSelectionRange(start, end); // Selected start position console.log(tc.selectionStart); // Selected end position console.log(tc.selectionEnd); var str = "huangbiao"; var tclen = tc.value.length; tc.value = tc.value.substr(0, tc.selectionStart) + str + tc.value.substring(tc.selectionStart, tclen); } function getSelectObj() {
// Get the object selected on the user page var selObj = window.getSelection(); // call Selection.toString() Method returns plain text in the selected area . window.alert(selObj); } function getRangeObj() {
var selObj = window.getSelection(); // obtain Range object var range = selObj.getRangeAt(0); console.log(range); } </script>
<body>
<textarea rows="5" name="s1" cols="27" id="mytextarea">
Aim by clicking the button on the page button stay textarea Insert text where the cursor stays in the </textarea >
<ul>
<li>
<button onclick="selectAll()">
select all
</button>
</li>
<li>
<button onclick="add('huangbiao')"> Add the specified string </button>
</li>
<li>
<button onclick="selectPos()">
Customize the selected location
</button>
</li>
<li>
<button onclick="getSelectObj()">
Gets the selected value
</button>
</li>
<li>
<button onclick="getRangeObj()">
Get the selected Range object
</button>
</li>
</ul>
</body>
</html>
边栏推荐
- 国信证券股票账户开户安全吗?请问。
- 还没弄明白微服务数据架构事务管理+ACID+一致性+CAP+BASE理论吗,看完彻底解决疑惑
- API encapsulation of uniapp applet
- As a software testing engineer, how do you think to ensure software quality?
- Is it safe for Guosen Securities to open a stock account? Excuse me?
- laravel8实现图片验证码
- 国信证券股票开户是安全的吗?
- turtlebot+lms111+gmapping实践
- Solving error: creating window glfw error: glew initialization error: missing GL version
- 两种方法实现pycharm中代码回滚到指定版本(附带截图展示)
猜你喜欢

Stream竟然还有应用进阶学习?作为程序员的你知道吗

测一测你的挣钱能力有多强?未来的你将从事什么职业?

数据采集系统网关采集工厂效率

Summary of common functions in Oracle Database

一次性讲清楚 Handler 可能导致的内存泄漏和解决办法 | 开发者说·DTalk

It's not easy to understand the data consistency of the microservice architecture for the first time after six years as a programmer

Reading the "clean" series for the first time, I didn't think it was a good book

楼宇自动化专用BACnet网关BL103

What if the CPU temperature of Dell computer is too high

分享自己平時使用的socket多客戶端通信的代碼技術點和軟件使用
随机推荐
英語中的九大詞性與九大時態
Garbage collection mechanism
Two common ways for orcale to clear table data
阻止深度神经网络过拟合(Mysteries of Neural Networks Part II)
Summary of common functions in Oracle Database
使用KVM虚拟化部署EVE-NG
golang项目依赖管理工具go vendor,go mod
Shell operator
哈希錶、哈希沖突
Is it safe for Guosen Securities to open an account?
Share the code technology points and software usage of socket multi client communication
【世界历史】第二集——文明的曙光
Mise en place d'un Cluster kubernets avec plusieurs serveurs Cloud
打新债是不是不安全
Deeply understand the mathematics behind deep neural networks (mysteries of neural networks Part I)
算力&NFT交易平台F3.xyz旗下独家权益NFT项目Hash Eagle将盛大发行
Numpy库使用入门
None of the MLIR optimization passes are enabled (registered 2) solutions
sigmoid函数sigmoid求导
Common formatting methods for amount numbers