晚上好,我有以下代码:
https://codepen.io/anon/pen/YbxwVd
在输入内容时,我尝试填充进度条。但是,正如您在Codepen中看到的那样,它不能很好地工作。有时,它在不应该填充时填充。 请帮助我,如果有更好的方法可以帮助我,
HTML
<div class="content-progressbar">
<div class="progressbar" id="progressbar"></div>
</div>
<form id="form" method="post" action="">
<input id="name" class="input" name="name" type="text" placeholder="Name" required>
<input id="surname" class="input" name="surname" type="text" placeholder="Surname" required>
<input id="email" class="input" name="email" type="email" placeholder="Email" required>
<input id="phone" class="input" name="phone" type="text" placeholder="Phone" required>
<input id="message" class="input" name="message" type="text" placeholder="Message" required>
<input type="submit" value="Send">
</form>
JavaScript
let progress = document.getElementById("progressbar");
let width = 0;
let form = document.getElementById("form");
let name = document.getElementById("name");
let surname = document.getElementById("surname");
let email = document.getElementById("email");
let phone = document.getElementById("phone");
let message = document.getElementById("message");
form.addEventListener("keyup", function() {
if (width <= 0) { width = 0; }
});
name.addEventListener("keyup", function() {
if (!name.checkValidity()) {
width = width - 20;
progress.style.width = width;
} else if (name.checkValidity() && name.value.length <= 1) {
width = width + 20;
progress.style.width = width + "%";
}
});
surname.addEventListener("keyup", function() {
if (!surname.checkValidity()) {
width = width - 20;
progress.style.width = width;
} else if (surname.checkValidity() && surname.value.length <= 1) {
width = width + 20;
progress.style.width = width + "%";
}
});
email.addEventListener("keyup", function() {
if (!email.checkValidity()) {
width = width - 20;
progress.style.width = width;
} else if (email.checkValidity()) {
width = width + 20;
progress.style.width = width + "%";
}
});
phone.addEventListener("keyup", function() {
if (!phone.checkValidity()) {
width = width - 20;
progress.style.width = width;
} else if (phone.checkValidity() && phone.value.length <= 1) {
width = width + 20;
progress.style.width = width + "%";
}
});
message.addEventListener("keyup", function() {
if (!message.checkValidity()) {
width = width - 20;
progress.style.width = width;
} else if (message.checkValidity() && message.value.length <= 1) {
width = width + 20;
progress.style.width = width + "%";
}
});
答案 0 :(得分:0)
我建议您以其他方式进行操作。 您可能希望保留一个布尔变量字典(对于每个输入),而不是每次增加或减小宽度的20%,无论它是否已完成,然后通过该字典计算宽度。
字典将如下所示:
var validInputsDict = {
"name" : true,
"surname" : true,
"email" : false
}
宽度的计算将为:
for (var key in validInputsDict) {
if (validInputsDict[key]) {
width+=20;
}
}