开发者社区> 问答> 正文

input 输入框如何实现当光标聚焦时部分文字被选中

我想实现以下的功能,如果html中的input标签中有如下的值时,当我的点击这个input中的某个字母时,和这个临近的字母被全选(遇到空格就不再选中),例如,我点击下面的这个input中的a时,它会把mail选中,而不会选中其他的字符,求大神如何设计js代码?

展开
收起
a123456678 2016-07-13 15:03:03 4597 0
1 条回答
写回答
取消 提交回答
  • <input id="i" type="text" value="One two three">
     
    $(document).ready(function(){
     
        $("#i").on("click",function(){
            var input = document.getElementById("i"),val = input.value;
            var click_position = getPosition(input);
             
            var start = val.lastIndexOf(" ",click_position);
            if(start == -1) start = 0;
            var end = val.indexOf(" ",click_position);
            if(end == -1) end = val.length;
         
            setSelection(input,start,end);
        });
     
         
        function setSelection(input, startPos, endPos) {
            input.focus();
            if (typeof input.selectionStart != "undefined") {
                input.selectionStart = startPos;
                input.selectionEnd = endPos;
            } else if (document.selection && document.selection.createRange) {
                input.select();
                var range = document.selection.createRange();
                range.collapse(true);
                range.moveEnd("character", endPos);
                range.moveStart("character", startPos);
                range.select();
            }
        }
        function getPosition (input) {
      var pos = 0;
      if (document.selection) {
        input.focus ();
        var selection = document.selection.createRange ();
        selection.moveStart ('character', -input.value.length);
        pos = selection.text.length;
      }
      else if (input.selectionStart || input.selectionStart == '0')
        pos = input.selectionStart;
      return pos;
    }
         
    })
    2019-07-17 19:55:38
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载