我找到了这个名为"simple- keyboard“的虚拟键盘,它只适用于一个输入栏。来自键盘的输入仅插入到第一个文本字段。
HTML
<input type="text" name="firstname" placeholder="Your name.." class="input">
<input type="text" name="lastname" placeholder="Your last name.." class="input">
<div class="simple-keyboard"></div>Simple-Keyboard JS
let Keyboard = window.SimpleKeyboard.default;
let keyboard = new Keyboard({
onChange: input => onChange(input),
onKeyPress: button => onKeyPress(button)
});
// Update simple-keyboard when input is changed directly
document.querySelector(".input").addEventListener("input", event => {
keyboard.setInput(event.target.value);
});
console.log(keyboard);
function onChange(input) {
document.querySelector(".input").value = input;
console.log("Input changed", input);
}
function onKeyPress(button) {
console.log("Button pressed", button);
// If you want to handle the shift and caps lock buttons
if (button === "{shift}" || button === "{lock}") handleShift();
}
function handleShift() {
let currentLayout = keyboard.options.layoutName;
let shiftToggle = currentLayout === "default" ? "shift" : "default";
keyboard.setOptions({
layoutName: shiftToggle
});
}来源:https://hodgef.com/simple-keyboard/demos/
如何使用class="input"使其适用于所有输入字段?
发布于 2020-10-14 17:48:54
这个问题是因为querySelector()只返回一个与选择器匹配的项。如果存在多个,则只返回第一个。
要解决您的问题,您需要使用querySelectorAll(),它提供所有匹配元素的集合,然后您需要通过循环遍历该集合中的所有输入来初始化库。
document.querySelectorAll(".input").forEach(input => {
input.addEventListener("input", event => {
keyboard.setInput(event.target.value);
});
})每当我尝试输入时,它只会输入到第一个文本字段中...即使我在尝试键盘时选择了第二个输入栏...不工作
考虑到这一点,库可能不支持每个实例多个控件。相反,您可能需要为每个控件创建整个Keyboard实例。这也需要在循环中完成:
document.querySelector(".input").addEventListener("input", event => {
let keyboard = new Keyboard({
onChange: input => onChange(input),
onKeyPress: button => onKeyPress(button)
});
keyboard.setInput(event.target.value);
});https://stackoverflow.com/questions/64350530
复制相似问题