在只读 html 输入上显示插入符
show caret on readonly html input
我正在创建一个计算器,我想在浏览器和移动设备上将其用作渐进式网络应用程序。我创建了自己的输入按钮,不想在移动设备上看到虚拟键盘。出于这个原因,我在 input
.
上使用属性 readonly
我想显示光标,以便用户知道将在何处插入数字或运算符。
不幸的是,只读输入仅在 firefox 移动版中显示光标,在 chrome 移动版中不显示。所以我不能依赖内置游标。
我需要一种方法来显示输入字段的光标,同时在单击输入字段时虚拟键盘未打开。
为了解决这个问题,我实现了自己的插入符号。我创建了一个 div,宽度为 1px,高度合适。 #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";
}
我正在创建一个计算器,我想在浏览器和移动设备上将其用作渐进式网络应用程序。我创建了自己的输入按钮,不想在移动设备上看到虚拟键盘。出于这个原因,我在 input
.
readonly
我想显示光标,以便用户知道将在何处插入数字或运算符。
不幸的是,只读输入仅在 firefox 移动版中显示光标,在 chrome 移动版中不显示。所以我不能依赖内置游标。
我需要一种方法来显示输入字段的光标,同时在单击输入字段时虚拟键盘未打开。
为了解决这个问题,我实现了自己的插入符号。我创建了一个 div,宽度为 1px,高度合适。 #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";
}