我正在制作一个注册表单,当密码和确认密码匹配时,注册按钮在悬停时变为绿色,但是当您将鼠标悬停在该按钮上时,当它为绿色并从密码字段中删除一个数字时(所以密码和确认不匹配)并且您移开鼠标按钮保持绿色而不是变回其原始颜色。
密码匹配时按钮为绿色
密码不匹配时按钮保持绿色
代码笔:https://codepen.io/makeyka/pen/oVQPOV
HTML:
<form>
<p class="font"><span id="movePassword">Password</span></p>
<input id="password" type="password" name="password" placeholder="Password.." onfocus="this.placeholder=''" onblur="this.placeholder='Password..'" required>
<p class="font"><span id="movePassword">Confirm Password</span></p>
<input id="confirm_password" type="password" name="password" placeholder="Confirm.." onfocus="this.placeholder=''" onblur="this.placeholder='Confirm..'" onkeyup="check();" required><span id="msg"></span>
<br><br>
<input type="submit" name="submit" value="SIGN UP" id="submit">
</form>
CSS:
#msg {
left: 3%;
font-size: 1.5em;
font-weight: bold;
position: relative;
}
#submit {
position: relative;
left: 3%;
width: 120px;
color: #4e5463;
background-color: #e8ecf7;
cursor: pointer;
}
JS:
var check = function() {
if (document.getElementById("password").value == document.getElementById("confirm_password").value) {
document.getElementById("msg").style.color = "#009FFD"; // Green
document.getElementById("msg").innerHTML = "✔"; // Sign
document.getElementById("submit").disabled = false; // Able to login (passwords match)
$("#submit").mouseenter(function() {
$(this).css("background", "#009FFD").css("borderRadius", "10px").css("color", "#423d3d"); // Green button background
}).mouseleave(function() {
$(this).css("background", "#e8ecf7").css("borderRadius", "0px").css("color", "#4e5463"); // Button default background color
});
} else {
document.getElementById("msg").style.color = "red";
document.getElementById("msg").innerHTML = "⚠"; // Sign
document.getElementById("submit").disabled = true; // Unable to login (passwords do not match)
}
}
最佳答案
发生这种情况是因为 mouseenter and mouseleave events don't work on disabled elements .当密码不匹配时,您禁用提交按钮,这意味着 mouseleave
永远不会被触发,样式也永远不会恢复正常。
您可以使用 css enabled
和 hover
属性代替 jquery 的 mouseenter
和 mouseleave
来解决这个问题。
在你的CSS中,添加这条规则:
#submit:enabled:hover {
background-color: #009FFD;
border-radius: 10px;
color: 423d3d;
}
然后在您的 javascript 中,删除您的事件监听器:
var check = function() {
if (document.getElementById("password").value == document.getElementById("confirm_password").value) {
document.getElementById("msg").style.color = "#009FFD"; // Green
document.getElementById("msg").innerHTML = "✔"; // Sign
document.getElementById("submit").disabled = false; // Able to login (passwords match)
} else {
document.getElementById("msg").style.color = "red";
document.getElementById("msg").innerHTML = "⚠"; // Sign
document.getElementById("submit").disabled = true; // Unable to login (passwords do not match)
}
}
关于javascript - 如何防止css为元素着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55290127/