zoukankan      html  css  js  c++  java
  • 控制input输入框光标的位置

    一:理解input, textarea元素在标准浏览器下两个属性selectionStart, selectionEnd。

    selectionStart: 该属性的含义是 选区开始的位置;
    selectionEnd: 选区结束的位置。
    两个值默认都是为0。
    注意: 该属性在chrome,safari和firefox都有用,标准浏览器下使用这两个属性。
    我们先来看看如下代码,打印下如下可以看到:

    <!DOCTYPE html>
         <html>
            <head>
              <meta charset="utf-8">
              <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
              <title>标题</title>
            </head>
            <body>
              <input id="inputId" type="text" oninput="inputFunc()" onkeyup="keyupFunc()"/>
              <textarea id="textareaId" oninput="textareaFunc()"></textarea>
              <script>
                var inputId = document.getElementById("inputId");
                console.log(inputId.value);
                console.log(inputId.selectionStart);
                console.log(inputId.selectionEnd);
    
                function inputFunc() {
                  console.log(inputId.value);
                  console.log(inputId.selectionStart);
                  console.log(inputId.selectionEnd);
                }
                function textareaFunc() {
                  var textareaId = document.getElementById('textareaId');
                  console.log(textareaId.selectionStart);
                  console.log(textareaId.selectionEnd)
                }
              </script>
            </body>
        </html>

    查看效果

    上面两个属性都代表了 选中区域的左右边界。默认值都是为0,当我们使用 focus()方法时,默认的光标在文本框的开头位置。我们可以如下设置该属性值如下:

    input.selectionStart = 0; // 选中区域左边界
    input.selectionEnd = input.value.length; // 选中区域的右边界

    上面的代码可以选中输入框的全部内容, 等同于input.select();
    那么我们如何获取选中的文本内容呢?我们可以使用 substring方法截取字符串;比如如下代码:
    var text = input.value.substring(input.selectionStart, input.selectionEnd);
    比如如下demo,页面上默认有一个输入框,然后输入框默认有值,然后通过上面两个属性selectionStart,selectionEnd 来选中文本,然后通过substring方法输出input的文本。如下代码:

    <!DOCTYPE html>
       <html>
          <head>
            <meta charset="utf-8">
            <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
            <title>标题</title>
          </head>
          <body>
            <input id="inputId" type="text" value="aaabbbbccccdddd"/>
            
            <script>
              var inputId = document.getElementById('inputId');
              inputId.selectionStart = 2;
              inputId.selectionEnd = inputId.value.length;
              var text = inputId.value.substring(inputId.selectionStart, inputId.selectionEnd);
              alert(text); // 从第三个字符开始 因此输出 abbbbccccdddd
              
            </script>
          </body>
      </html>

    查看效果 

    因此我们可以对标准浏览器下 对光标位置进行设置,比如页面初始化的时候,我们可以设置光标的位置:如下代码:

    input.selectionStart = 1;  // 选中区域的左边界
    input.selectionEnd = input.value.length - 1; // 选中区域的右边界

    如上代码,在页面初始化的时候 可以设置光标的位置。

    IE浏览器下如何实现的呢?
    IE浏览器下创建一个文本选取对象,使用 createTextRange()方法;如下代码:

    var range = input.createTextRange();

    上面的这个选区对象默认包含了input的全部文本内容。但是该选区对象的内容并不会选中。因此需要调用 select()方法;如下代码:
    range.select();
    我们也可以使用 range.text属性得到选中的文字。
    对于标准浏览器下可以使用 selectionStart和selectionEnd属性的方法拿到选区的开始位置和结束位置,那么对于IE浏览器下可以使用 moveStart和moveEnd方法。

    二:理解 IE浏览器下的 moveStart 和 moveEnd 方法

    这两个方法的选区对象包含input的全部文本内容,所以它的左右边界就是文本的开头和结束位置。

    moveStart方法的含义是: 用来移动左边界。如下代码:

    rangeObj.moveStart("character", 2); // 最左边界右移2个字符
    rangeObj.select(); // 将range包含的区域选中

    上面两个方法都需要传入两个参数,第一个参数的可选值有 character(根据字符来偏移), word, sentence, textedit, 第二个参数代表偏移的多少,正负表示方向。
    左边界最初默认为0,右边界默认是文本内容的长度值。

    注意:rangeObj.select() 方法, 该方法是把range对象中的内容选中;

    三:理解setSelectionRange

    该方法可以理解为input元素的方法:
    HTMLInputElement.setSelectionRange();
    该方法的作用是:可以为当前元素内的文本设置选中范围。简单的说,可以通过设置起始于终止位置,来选中一段文本中的一部分。使用方式如下:
    inputElement.setSelectionRange(selectionStart, selectionEnd, [selectionDirection]);
    参数的含义如下:
    selectionStart: 第一个被选中的字符的序号(index), 从0开始的。
    selectionEnd: 被选中的最后一个字符的
    selectionDirection: 选择的方向,可选值为 forward, backward, 或 none.

    我们下面来做一个demo,当鼠标focus input框的时候,文本的内容会被选中,如下代码演示一下:

    <!DOCTYPE html>
      <html>
          <head>
            <meta charset="utf-8">
            <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
            <title>标题</title>
          </head>
          <body>
            <input id="inputId" type="text" value="这是一段测试文本"/>
            
            <script>
              var inputId = document.getElementById('inputId');
              inputId.addEventListener('focus', function() {
                if(inputId.setSelectionRange) {
                  inputId.setSelectionRange(0, inputId.value.length);
                }
              });
            </script>
          </body>
      </html>

    查看效果

    该方法的在浏览器下的兼容性如下

    属性                    chrome           firefox       IE     opera      safari
    setSelectionRange       1.0              1.0          9       8.0        支持
    selectionDirection      15               8.0                             支持

    一般情况下,主流浏览器都支持的,对于selectionDirection该属性,兼容性虽然不是很好,但是不应该该方法的使用。

    控制光标位置

    如何通过该方法来控制input标签的光标位置呢?比如在页面初始化的时候,我想默认选中部分文本,如何控制?
    下面我们来继续做一个demo,通过点击(focus事件),来选中input值(除了第一个字符和最后两个字符),其他的字符都选中,代码改成如下:
    inputId.setSelectionRange(1, inputId.value.length - 2);
    所有代码如下:

    <!DOCTYPE html>
      <html>
          <head>
            <meta charset="utf-8">
            <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
            <title>标题</title>
          </head>
          <body>
            <input id="inputId" type="text" value="这是一段测试文本"/>
            
            <script>
              var inputId = document.getElementById('inputId');
              inputId.addEventListener('focus', function() {
                if(inputId.setSelectionRange) {
                  inputId.setSelectionRange(1, inputId.value.length - 2);
                }
              });
            </script>
          </body>
      </html>

    查看效果 

    通过上面的基础知识点,我们可以做如下的demo
    JS获取文本焦点光标位置,选中起始位置,终止位置 和 选中内容的demo;

    代码如下:

    <!DOCTYPE html>
      <html>
          <head>
            <meta charset="utf-8">
            <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
            <title>标题</title>
          </head>
          <body>
            <p>
              <label>点击文本框内容触发事件</label>
              <input type="text" id="txt" value="abcdefghijklmn" onclick="getSelectPosition(this);">
            </p>
            <p>
              <label>焦点位置:</label>
              <input type="text" id="txt1" value="">
            </p>
            <p>
              <label>选中起始位置:</label>
              <input type="text" id="txt2" value="">
              <label>选中结束位置:</label>
              <input type="text" id="txt3" value="">
            </p>
            <p>
              <label>选中内容:</label>
              <input type="text" id="txt4" value="">
            </p>
            <script>
              function getSelectPosition($this) {
                var input1 = document.getElementById("txt1");
                var input2 = document.getElementById("txt2");
                var input3 = document.getElementById("txt3");
                var input4 = document.getElementById("txt4");
    
                var emptyValue = -1;
                var selectStart;
                var selectEnd;
                var pos;
                var selectText;
                if ($this.setSelectionRange) {
                  // 标准浏览器
                  selectStart = $this.selectionStart;
                  selectEnd = $this.selectionEnd;
                  if (selectStart == selectEnd) {
                    pos = selectStart;
                    selectStart = emptyValue;
                    selectEnd = emptyValue;
                  } else {
                    pos = emptyValue;
                  }
                  selectText = $this.value.substring(selectStart,selectEnd);
                } else {
                  // IE浏览器
                  var range = document.selection.createRange();
                  selectText = range.text;
                  range.moveStart("character",-$this.value.length);
                  pos = range.text.length;
                  selectStart = pos - (selectText.length);
                  selectEnd = selectStart + (selectText.length);
    
                  if(selectStart != selectEnd){
                    pos = emptyValue;
                  }else{
                    selectStart = emptyValue;
                    selectEnd = emptyValue;
                  }
                }
                input1.value = pos;
                input2.value = selectStart;
                input3.value = selectEnd;
                input4.value = selectText;
              }
            </script>
          </body>
      </html>

    查看效果

    input 输入框按键盘上键的时候 光标会先到前面去,然后跳到后面来的解决方案如下:

    keydown+e.preventDefault(阻止默认事件)的操作来解决;如下代码:

    <!DOCTYPE html>
       <html>
          <head>
            <meta charset="utf-8">
            <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
            <title>标题</title>
          </head>
          <body>
            <input id="inputId" type="text" value="键盘箭头上下移"/>
            <script>
              var inputId = document.getElementById('inputId');
              inputId.addEventListener('keyup', function(e) {
                
              });
              inputId.addEventListener('keydown', function(e) {
                e.preventDefault();
              });
            </script>
          </body>
      </html>
  • 相关阅读:
    winfrom 获取当前系统时间
    netcore3.1API+efcore快速搭建
    php
    php
    php
    php-array的相关函数使用
    php-正则表达式
    vim的复制与粘贴
    vim的多窗口和文件切换操作
    laravel教程中出现500问题
  • 原文地址:https://www.cnblogs.com/tugenhua0707/p/7434935.html
Copyright © 2011-2022 走看看