Get cursor position (in characters) within a text Input field

后端 未结 9 1238
孤城傲影
孤城傲影 2020-11-22 01:22

How can I get the caret position from within an input field?

I have found a few bits and pieces via Google, but nothing bullet proof.

Basically something lik

9条回答
  •  情歌与酒
    2020-11-22 01:33

    const inpT = document.getElementById("text-box");
    const inpC = document.getElementById("text-box-content");
    // swch gets  inputs .
    var swch;
    // swch  if corsur is active in inputs defaulte is false .
    var isSelect = false;
    
    var crnselect;
    // on focus
    function setSwitch(e) {
      swch = e;
      isSelect = true;
      console.log("set Switch: " + isSelect);
    }
    // on click ev
    function setEmoji() {
      if (isSelect) {
        console.log("emoji added :)");
        swch.value += ":)";
        swch.setSelectionRange(2,2 );
        isSelect = true;
      }
    
    }
    // on not selected on input . 
    function onout() {
      // الافنت  اون كي اب 
      crnselect = inpC.selectionStart;
      
      // return input select not active after 200 ms .
      var len = swch.value.length;
      setTimeout(() => {
       (len == swch.value.length)? isSelect = false:isSelect = true;
      }, 200);
    }

    Try it !

提交回复
热议问题