代码之家  ›  专栏  ›  技术社区  ›  SeaBass

只在焦点上显示输入中的最后3个字符?

  •  1
  • SeaBass  · 技术社区  · 7 年前

    我有输入,其中有小时和分钟,但我只希望在输入集中时显示分钟。这可能吗?

    我当前的方法使用jQuery来添加完整时间,但最好将完整时间作为整个时间的值,并只显示必要的内容。

    此外,由于这个原因,光标不会出现在您在输入中单击的位置(而是显示在末尾)。至少在FF中)。

    其他更聪明的想法?用css是不可能的,对吧?未聚焦时,将最后3个字符的颜色设置为透明或类似。

    $('input').on('focus', function(e) {
      var full_time = $(this).attr('data-full-time');
      $(this).val(full_time);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" data-full-time="12:30" data-short-time="12" value="12" />
    3 回复  |  直到 7 年前
        1
  •  3
  •   Michael Kolber    7 年前

    要使光标位于正确的位置,可以使用假表单字段。这主要是CSS,只有JS来同步字段。(从你的例子来看,我认为你的意思是你只想要 小时 分钟 .)

    $('#real').on('input', function(e) {
      $('#fake').val($(this).val().split(':')[0]);
    });
    .input-container {
      position: relative;
    }
    
    .input-container input {
      position: absolute;
    }
    
    #fake {
      pointer-events: none;
    }
    
    #real {
      opacity: 0;
    }
    
    #real:focus {
      opacity: 1;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="input-container">
      <input id="fake" type="text" value="12" />
      <input id="real" type="text" value="12:30" />
     </div>
        2
  •  0
  •   pseudobbs    7 年前

    HTML格式:

    <input id="timeInput" value="12:30" onfocus="showMinutesOnly()" onblur="showWholeTime()"/>
    

    var wholeTimeString;
    var minutes;
    
    function showMinutesOnly(){
      wholeTimeString = document.getElementById("timeInput").value;
      minutes = wholeTimeString.substring(wholeTimeString.indexOf(":")+1);
    
      document.getElementById("timeInput").value = minutes;
    }
    
    function showWholeTime(){
      document.getElementById("timeInput").value = wholeTimeString;
    }
    

    例子: http://jsbin.com/rumaveguwe/1/edit?html,js,console,output

        3
  •  0
  •   gavgrif    7 年前

    $('input').on('focus', function(e) {
      var time = $(this).attr('data-time');
      $(this).val(time);
    });
    
    $('input').on('blur', function(e) {
      var time = $(this).attr('data-time').split(":")[0];
      $(this).val(time);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" data-time="12:30"  autofocus/>