Home >Web Front-end >JS Tutorial >Get the cursor position of the text box and locate the text box through js, complete code attached
The cursor of the text box (input or textarea) cannot be modified in style (except by modifying the cursor color through color). But the author hopes that when individuals create their own websites, the cursor in the text box will have their own style. So, try to simulate the cursor of the text box and design the cursor with your own style. The following are the author's personal thoughts on obtaining the cursor position of the text box and positioning it in the text box through js.
【************************Basic Ideas******************************】
For keyboard operations, the basic operations of the cursor are nothing more than the three most basic keys: left arrow (left arrow), right arrow (right arrow) and backspace key (backspace).
Left arrow: Move the cursor to the left, add characters or delete characters
Right arrow: Move the cursor to the right, add characters or delete characters
Backspace key: Delete characters
【******** When talking about how to implement the basic functions of the cursor through JS, let’s first introduce some html and css **** ****】
***html***
<p class="cursor_module"> <p class="cursor_content"></p><span class="cursor"></span> </p>
Note: The above HTML format only simulates the cursor, and you still need to rely on form elements to input characters. On the page, the author will hide the real form elements and only display the html that simulates the cursor
<form id="chatting_form" class="clearfix" enctype="application/x-www-form-urlencoded"> <label for="chatting_msg"></label><input type="text" id="chatting_msg" autofocus name="chatting_msg"> </form>First line: Simulation Cursor Second line: Cursor in form element
##***CSS***
.cursor_module{ position: relative; } .cursor_content{ position: absolute; top: 0; left: 0; width: auto; max-width: 90%; word-wrap: break-word; overflow: hidden; display: inline-block; white-space: pre; } .cursor{ position: absolute; top: 0; left: 0; width: 6px; height: 16px; display: inline-block; background: green; z-index: 1000; }
【****************************** Officially starting to introduce JS ************ **********************】
**Left Arrow**
1. No text is entered, press the left arrow, the cursor is still in leftThe value is 0s position.
2. After inputting text (ie: the value value of the text box is not empty), press the left arrow and the cursor move to the left.
Restrictions: When moved to left the value is ## At the position of #0, even if you continue to press the left arrow, the cursor will not continue to move to the left [The cursor can only move if its left value must be greater than 0]
if(cCode===37 && chatting_msg.value!=''){ if(aSpan_l>0){ aSpan.style.left=aSpan_l-aSpan_w+'px'; } }
**Right Arrow**
##1. If there is no text input, press the right arrow, and the cursor is still at the position where theleft**Backspace key**value is 0. 2. After entering text, press the right arrow to move the cursor to the right.
Restrictions: When moving behind the last character of the text content, the cursor will not continue even if you continue to press the right arrow Move right [When the left value of the cursor is equal to the width of the p element, the cursor is at the position of the last character]
else if(cCode===39 && chatting_msg.value!=''){ aSpan.style.left=aSpan_l+aSpan_w+'px'; if(aSpan_l===aP_width){ aSpan.style.left=aP_width+'px'; } }
1. When no characters exist, press the delete key to simulate the cursor and It will not move to the left and stay at the original position
**Other keys**2. Delete a character and the cursor position will move one unit to the left (in this example it is
6px);
else if(cCode===8){ if(chatting_msg.value!=''){ aP.innerHTML=chatting_msg.value; if(aSpan_l!=0){ aSpan.style.left=aSpan_l-aSpan_w+'px'; } }else{ aSpan.style.left=0; } //if enter backspace,remove move event JM.removeHandler(chatting_msg,'input',move,false); }
问题:为什么笔者会将输入框的value值赋值给p元素的innerHTML这行代码【aP.innerHTML=chatting_msg.value;】放置在 keyup 事件处理程序中? 在事件为keydown(或keypress)情况下,执行将文本框的value值赋值给p元素的innerHTML,实际情况下,如果输入两个字符 ‘ab’,但是在p元素内显示的就只有第一个字符 ‘a’。 简单来说就是,keydown或keypress对于文本框本身而言显示字符是没有问题,就是你输入多少个字符就显示多少个字符,但是对于要将文本内容显示在p元素内,则会 “反应慢一拍” 。 【提示:笔者对其他非字符键还未作任何处理】 【************************* 补充 ******************************】 1、为了在按下退格键时不影响光标的正确定位,需要在按下退格键时把 ”move“函数取消掉 -------JM.removeHandler(chatting_msg,'input',move,false); 2、代码中存在的JM.xxxx,是笔者的代码库 JM.addHandler(...):添加事件处理程序 JM.removeHandler(...):删除事件处理程序 JM.getStyle(...):获取计算机样式的值 >>>>>>>>>>>具体的代码可以参考《JavaScript高级程序设计》这本书 3、笔者自定义的这个光标现在只适合于输入英文、数字、标点符号,暂时不支持输入中文 《《《《《《《 完整代码 》》》》》》》》》 更多关于通过js获取文本框光标位置及定位到文本框的方法请关注php中文网!else{
//show value by keyup not keydown,because keydown will slow step;
JM.addHandler(chatting_msg,'keyup',function () {
aP.innerHTML=chatting_msg.value;
},false);
JM.addHandler(chatting_msg,'input',move,false);
}
var move=function () {
var aSpan=JM.getEles('.cursor')[0],
aSpan_l=parseInt(JM.getStyle(aSpan,'left')),
aSpan_w=parseInt(JM.getStyle(aSpan,'width'));
aSpan.style.left=aSpan_l+aSpan_w+'px';
};
var Cursor=(function () {
var chatting_msg=JM.getEles('[name=\'chatting_msg\']')[0];
var cursor_module=JM.getEles('.cursor_module')[0];
var chatting_footer=JM.getEles('.chatting_footer')[0];
//create elements
var cP=document.createElement('p');
var cSpan=document.createElement('span');
JM.addClass(cP,'cursor_content');
JM.addClass(cSpan,'cursor');
JM.addNodes(cursor_module,cSpan);
JM.addNodes(cursor_module,cP);
//keydown
JM.addHandler(chatting_msg,'keydown',function (event) {
var ev=JM.getEvent(event),
cCode=JM.getCharCode(ev);
var aP=JM.getEles('.cursor_content')[0],
aSpan=JM.getEles('.cursor')[0];
var aP_width=parseInt(JM.getStyle(aP,'width'));//get aP real width
var aSpan_l=parseInt(JM.getStyle(aSpan,'left')),//get span left
aSpan_w=parseInt(JM.getStyle(aSpan,'width'));//get span width
var val=chatting_msg.value;
//left arrow
//没有value值,按左箭头不动
//有value值,按右箭头,光标向左移,但移到前面一个字符的后面就不可以再移动
if(cCode===37 && chatting_msg.value!=''){
if(aSpan_l>0){
aSpan.style.left=aSpan_l-aSpan_w+'px';
}
}
//right arrow
//没有value值,按右箭头不动
//有value值,按右箭头,光标向右移,但移到最后一个字符的后面就不可以再移动
else if(cCode===39 && chatting_msg.value!=''){
aSpan.style.left=aSpan_l+aSpan_w+'px';
if(aSpan_l===aP_width){
aSpan.style.left=aP_width+'px';
}
}
//backspace
else if(cCode===8){
if(chatting_msg.value!=''){
aP.innerHTML=chatting_msg.value;
if(aSpan_l!=0){
aSpan.style.left=aSpan_l-aSpan_w+'px';
}
}else{
aSpan.style.left=0;
}
//if enter backspace,remove move event
JM.removeHandler(chatting_msg,'input',move,false);
}
else{
//show value by keyup not keydown,because keydown will slow step;
JM.addHandler(chatting_msg,'keyup',function () {
aP.innerHTML=chatting_msg.value;
},false);
JM.addHandler(chatting_msg,'input',move,false);
}
},false);
//move cursor in the text
var move=function () {
var aSpan=JM.getEles('.cursor')[0],
aSpan_l=parseInt(JM.getStyle(aSpan,'left')),
aSpan_w=parseInt(JM.getStyle(aSpan,'width'));
aSpan.style.left=aSpan_l+aSpan_w+'px';
};
})();