[英]show caret on readonly html input
我正在创建一个计算器,我想在浏览器和移动设备上用作渐进式网络应用程序。 我创建了自己的输入按钮,不想在移动设备上看到虚拟键盘。 出于这个原因,我在input
上使用了readonly
属性。
我想显示光标,以便用户知道将插入数字或运算符的位置。
不幸的是,只读输入仅在 firefox mobile 中显示光标,而不在 chrome mobile 中显示。 所以我不能依赖内置的游标。
在单击输入字段时,我需要一种方法来显示输入字段的光标,而虚拟键盘未打开。
为了解决这个问题,我实现了自己的插入符号。 我创建了一个 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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.