【发布时间】:2019-09-17 18:34:49
【问题描述】:
我基本上试图让这三个文本输入代表 00h 00m 00s 以供我的计时器获取用户输入。我希望能够制作谷歌计时器(如果你只是在谷歌中输入计时器,你可以看到这个计时器)但我被困在正确导航上 - 当用户输入两位数字然后专注于下一个输入并且没有“表单”时元素跳出循环。但是,我不断收到“无法读取 null 的属性 'firstElementChild'”。
另外,我希望看到的是当用户输入数字(例如 01 : 30: 00)然后按回车键时,我希望能够获得用户值,这样我就可以根据然而,用户输入,监听“Enter”键触发提交的按键事件似乎不起作用,并且 e.preventDefault() 也不起作用..
<div class="form-container">
<form class="1" action="">
<input class="1" type="text" maxlength="2" placeholder="00:">
</form>
<form class="2" action="">
<input class="2" type="text" maxlength="2" placeholder="00:">
</form>
<form class="3" action="">
<input class="3" type="text" maxlength="2" placeholder="00:">
</form>
</div>
formContainer.addEventListener('keyup', function(e){
let target = e.srcElement || e.target;
let targetValue = target.attributes["maxlength"].value
let maxLength = parseInt(targetValue, 10);
let currentLength = target.value.length;
if(currentLength >= maxLength) {
let next = target;
let nextInputParent = target.parentElement.nextElementSibling
let nextInputInNextSibling = nextInputParent.firstElementChild
while (next = nextInputInNextSibling){
if (next.parentElement == null){
break;
}
if (next.tagName.toLowerCase() === "input") {
next.focus();
break;
}
}
}
// Move to previous field if empty (user pressed backspace)
else if (currentLength === 0) {
let previous = target;
let previousInputInPreviousSibling = target.parentElement.previousElementSibling.children[0]
while (previous = previousInputInPreviousSibling) {
if (previous == null)
break;
if (previous.tagName.toLowerCase() === "input") {
previous.focus();
break;
}
}
}
})
form.addEventListener('keydown', function(e){
if(e.key == "Enter" || e.keyCode == 13){
console.log("submit");
e.preventDefault()
form.submit()
let userInput = inputEl.value
let countdown = 60 * userInput
timer = new Timer(countdown, userInput)
timer.start()
toggleStartTimer.textContent = "stop"
timer.isOn = true
}
})
【问题讨论】:
标签: javascript forms input