【发布时间】:2020-01-21 09:59:33
【问题描述】:
我正在开发一个实时 HTML 编辑器。它基本上适用于移动用户。所以我制作了一个带有 HTML 标签的虚拟键盘。但是,我面临一个问题: 键盘只打印另一个标签末尾的标签。所以它没有按我想要的那样工作。
这里是代码。
(function() {
'use strict';
var i, c, t, delay = 5000,
kb = document.getElementById('keyboard');
/* get all the input elements within the div whose id is "keyboard */
i = kb.getElementsByTagName('input');
/* loop through all the elements */
for (c = 0; c < i.length; c++) {
/* find all the the input type="button" elements */
if (i[c].type === 'button') {
/* add an onclick handler to each of them and set the function to call */
i[c].addEventListener('onclick', makeClickHandler(c));
}
}
/* this is the type="reset" input */
document.getElementById('clear').addEventListener('click',
function() {
/* remove all the characters from the input type="text" element */
document.getElementById('text').value = '';
}, false);
function makeClickHandler(c) {
i[c].onclick = function() {
/* find the non-text button which has an id */
if (i[c].id === 'back') {
/* remove last character from the input the type="text" element using regular expression */
document.getElementById('text').value =
document.getElementById('text').value.replace(/.$/, '');
}
/* find the text buttons */
else {
/* add characters to the input type="text" element */
document.getElementById('text').value += this.value.toLowerCase();
}
};
}
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
function logout() {
kb.classList.remove('show');
kb.classList.add('hide');
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, delay)
}
resetTimer();
})();
<div id="keyboard" class="show">
<div>
<input type="button" value="Q">
<input type="button" value="W"> .........
<input type="button" value="V">
<input type="button" value="B">
<input type="button" value="N">
<input type="button" value="M">
</div>
<div>
<input id="back" type="button" value="←">
<input id="space" type="button" value=" ">
<input id="clear" type="reset" value="clear">
</div>
<div>
<label>Track Search</label> - <input id="text" type="text">
</div>
<!-- #keyboard -->
</div>
使用此代码,我只能在最后一个打印字符之后打印。但我想要这样(| 表示光标位置),
An|ant
这里我在ant之前写了An。
但它会这样打印:
ant An|
我可以做些什么来解决这个问题?
【问题讨论】:
-
对我来说很好
-
没有。它不是。写“公民”。然后尝试在“citizens”之前写“USA”。
标签: javascript html cursor-position virtual-keyboard