Home > Web Front-end > JS Tutorial > body text

Get the cursor position of the text box and locate the text box through js, complete code attached

PHPz
Release: 2017-03-30 15:27:32
Original
5512 people have browsed it

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>
Copy after login

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>
Copy after login

  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;
}
Copy after login

【****************************** 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!=&#39;&#39;){
      if(aSpan_l>0){
            aSpan.style.left=aSpan_l-aSpan_w+&#39;px&#39;;
      }
}
Copy after login

**Right Arrow**

##1. If there is no text input, press the right arrow, and the cursor is still at the position where the
left

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!=&#39;&#39;){
    aSpan.style.left=aSpan_l+aSpan_w+&#39;px&#39;;
         if(aSpan_l===aP_width){
              aSpan.style.left=aP_width+&#39;px&#39;;
          }
 }
Copy after login


**Backspace key**

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

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!=&#39;&#39;){
         aP.innerHTML=chatting_msg.value;
         if(aSpan_l!=0){
              aSpan.style.left=aSpan_l-aSpan_w+&#39;px&#39;;
            }
     }else{
            aSpan.style.left=0;
       }
            //if enter backspace,remove move event
            JM.removeHandler(chatting_msg,&#39;input&#39;,move,false);
  }  
Copy after login

**Other keys**

else{
       //show value by keyup not keydown,because keydown will slow step;
       JM.addHandler(chatting_msg,&#39;keyup&#39;,function () {
                aP.innerHTML=chatting_msg.value;
       },false);
       JM.addHandler(chatting_msg,&#39;input&#39;,move,false);
}
var move=function () {
    var aSpan=JM.getEles(&#39;.cursor&#39;)[0],
        aSpan_l=parseInt(JM.getStyle(aSpan,&#39;left&#39;)),
        aSpan_w=parseInt(JM.getStyle(aSpan,&#39;width&#39;));
    aSpan.style.left=aSpan_l+aSpan_w+&#39;px&#39;;
};
Copy after login

问题:为什么笔者会将输入框的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、笔者自定义的这个光标现在只适合于输入英文、数字、标点符号,暂时不支持输入中文

《《《《《《《 完整代码 》》》》》》》》》

var Cursor=(function () {
    var chatting_msg=JM.getEles(&#39;[name=\&#39;chatting_msg\&#39;]&#39;)[0];
    var cursor_module=JM.getEles(&#39;.cursor_module&#39;)[0];
    var chatting_footer=JM.getEles(&#39;.chatting_footer&#39;)[0];

    //create elements
    var cP=document.createElement(&#39;p&#39;);
    var cSpan=document.createElement(&#39;span&#39;);
    JM.addClass(cP,&#39;cursor_content&#39;);
    JM.addClass(cSpan,&#39;cursor&#39;);
    JM.addNodes(cursor_module,cSpan);
    JM.addNodes(cursor_module,cP);

    //keydown
    JM.addHandler(chatting_msg,&#39;keydown&#39;,function (event) {
        var ev=JM.getEvent(event),
            cCode=JM.getCharCode(ev);

        var aP=JM.getEles(&#39;.cursor_content&#39;)[0],
            aSpan=JM.getEles(&#39;.cursor&#39;)[0];

        var aP_width=parseInt(JM.getStyle(aP,&#39;width&#39;));//get aP real width

        var aSpan_l=parseInt(JM.getStyle(aSpan,&#39;left&#39;)),//get span left
            aSpan_w=parseInt(JM.getStyle(aSpan,&#39;width&#39;));//get span width

        var val=chatting_msg.value;
        //left arrow
        //没有value值,按左箭头不动
        //有value值,按右箭头,光标向左移,但移到前面一个字符的后面就不可以再移动
        if(cCode===37 && chatting_msg.value!=&#39;&#39;){
            if(aSpan_l>0){
                aSpan.style.left=aSpan_l-aSpan_w+&#39;px&#39;;  
            }
        }
        //right arrow
        //没有value值,按右箭头不动
        //有value值,按右箭头,光标向右移,但移到最后一个字符的后面就不可以再移动
        else if(cCode===39 && chatting_msg.value!=&#39;&#39;){
            aSpan.style.left=aSpan_l+aSpan_w+&#39;px&#39;;
            if(aSpan_l===aP_width){
                aSpan.style.left=aP_width+&#39;px&#39;;
            }
        }
        //backspace
        else if(cCode===8){
            if(chatting_msg.value!=&#39;&#39;){
                aP.innerHTML=chatting_msg.value;
                if(aSpan_l!=0){
                    aSpan.style.left=aSpan_l-aSpan_w+&#39;px&#39;;
                }
            }else{
                aSpan.style.left=0;
            }
            //if enter backspace,remove move event
            JM.removeHandler(chatting_msg,&#39;input&#39;,move,false);
        }
        else{
            //show value by keyup not keydown,because keydown will slow step;
            JM.addHandler(chatting_msg,&#39;keyup&#39;,function () {
                aP.innerHTML=chatting_msg.value;
            },false);
            JM.addHandler(chatting_msg,&#39;input&#39;,move,false);
        }
    },false);

    //move cursor in the text
    var move=function () {
        var aSpan=JM.getEles(&#39;.cursor&#39;)[0],
            aSpan_l=parseInt(JM.getStyle(aSpan,&#39;left&#39;)),
            aSpan_w=parseInt(JM.getStyle(aSpan,&#39;width&#39;));
        aSpan.style.left=aSpan_l+aSpan_w+&#39;px&#39;;
    };
})();
Copy after login

更多关于通过js获取文本框光标位置及定位到文本框的方法请关注php中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!