【问题标题】:show caret on readonly html input在只读 html 输入上显示插入符号
【发布时间】:2019-03-29 21:39:28
【问题描述】:

我正在创建一个计算器,我想在浏览器和移动设备上用作渐进式网络应用程序。我创建了自己的输入按钮,不想在移动设备上看到虚拟键盘。出于这个原因,我在input 上使用属性readonly

我想显示光标,以便用户知道数字或运算符将插入的位置。

不幸的是,只读输入仅在 firefox mobile 中显示光标,而不在 chrome mobile 中显示。所以我不能依赖内置的光标。

当点击输入字段时,我需要一种方法来显示输入字段的光标,而虚拟键盘未打开。

【问题讨论】:

    标签: javascript html css mobile


    【解决方案1】:

    为了解决这个问题,我实现了自己的插入符号。我创建了一个 1px 宽度和适当高度的 div。 #caret 相对于.input-group 定位。

    为方便起见,我在输入中使用等宽字体。所以每个字符都有相同的宽度。然后我只听输入上的任何事件并相应地更新插入符号的位置。 text-shadow 和透明的 color 使原始插入符号在 Firefox 移动设备上不可见。

    我的输入框向右对齐。

    更新 https://jsfiddle.net/9fr46y2w/3/

    HTML

    <div class="input-group">
      <input type="text" id="input" onclick="showCaret(this);">
      <div id="caret"></div>
    </div>
    

    CSS

    #input {
      color: transparent;
      font-family: monospace;
      font-size: 36px;
      height: 48px;
      margin: 0;
      padding: 0;
      text-align: right;
      text-shadow: 0 0 0 #yourTextColor;
      width: 100%;
    }
    
    .input-group {
      margin: 0;
      padding: 0;
      position: relative;
    }
    
    #caret {
      background: white;
      color: transparent;
      height: 41px;
      position: absolute;
      top: 4px;
      right:0;
      width: 1px;
    
      animation-duration: 1s;
      animation-name: blink;
      animation-iteration-count: infinite;
    }
    
    @keyframes blink {
      from {
        opacity: 1; 
      }
    
      49.9% {
          opacity: 1;
      }
      50% {
        opacity: 0;
      }
    
      99.9% {
          opacity: 0;
      }
    
      to {
        opacity: 1;
      }
     } 
    

    JavaScript

    function showCaret(input) {
      let widthSizeRatio = 21.6/36;
      let charWidth = widthSizeRatio * 36;
      let length = input.value.length;
      let cur = input.selectionStart;
    
      document.getElementById("caret").style.right = Math.floor((length - cur) * charWidth) + "px";
    }
    

    【讨论】:

    • 我注意到这个实现的一个小细节:改变位置后动画不会重置。因此,当在正确的时间单击时,光标似乎会稍后出现,因为它隐藏了 500 毫秒。所以一点改进是在改变位置时重置动画。
    猜你喜欢
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 2015-02-04
    相关资源
    最近更新 更多