gpt4 book ai didi

javascript - 加载/重新加载页面时隐藏验证输出标记 (✘) 符号隐藏

转载 作者:行者123 更新时间:2023-11-30 12:59:02 25 4
gpt4 key购买 nike

我将下面的代码与输入框上的 HTML5 模式匹配以及 CSS3 :invalid:valid 伪选择器一起使用,以显示验证的输出(有效值或不)在输入框旁边可用的 div.input-validation 中。这按预期工作,但它在页面加载本身和重新加载页面时显示验证标记(✘ - 无效输入)。我应该如何避免这种情况?

代码:

<style type="text/css">
input {
font-size: 1em;
padding: .3em;
border-radius: 3px;
margin: .2em;
}
input[type="text"]:valid {
color: green;
}
input[type="text"]:valid ~ .input-validation::before {
content: "\2714";
color: green;
}
input[type="text"]:invalid ~ .input-validation::before {
content: "\2718";
color: red;
}
.input-validation {
display: inline-block;
}
</style>
<?echo $passwordregister;?>
<input name="pw" autocomplete="off" type="text" id="pw" pattern="[a-zA-Z0-9]{6,22}" autofocus required >
<div class="input-validation"></div>

最佳答案

您可以使用以下任一选项在页面加载时隐藏无效值 (✘) 符号。

选项 1: 在页面加载时隐藏包含符号的 span,仅当输入发生某些 keypress 事件时才显示它文本框。

window.onload = function() {
var el = document.querySelectorAll("input[type='text']");
for (var i = 0; i < el.length; i++) {
el[i].onkeypress = showSymbol;
}

function showSymbol() {
this.nextElementSibling.style.display = "inline-block"; // display the span next to the input in which key was pressed.
}
}
input {
font-size: 1em;
padding: .3em;
border-radius: 3px;
margin: .2em;
}
input[type="text"]:valid {
color: green;
}
input[type="text"]:valid + .input-validation::before {
content: "\2714";
color: green;
}
input[type="text"]:invalid + .input-validation::before {
content: "\2718";
color: red;
}
.input-validation {
display: none;
}
<input name="pw" autocomplete="off" type="text" id="pw" class="new" pattern="[a-zA-Z0-9]{6,22}" autofocus required/> <span class="input-validation"></span>


选项 2: 根据特定类(例如 visited)的存在定义 CSS 规则,并仅在输入框中按下某个键时分配此类。

window.onload = function() {
var el = document.querySelectorAll("input[type='text']");
for (var i = 0; i < el.length; i++) {
el[i].onkeypress = showSymbol;
}

function showSymbol() {
this.classList.add("visited"); // add the visited class
}
}
input {
font-size: 1em;
padding: .3em;
border-radius: 3px;
margin: .2em;
}
input[type="text"].visited:valid {
color: green;
}
input[type="text"].visited:valid + .input-validation::before {
content: "\2714";
color: green;
}
input[type="text"].visited:invalid + .input-validation::before {
content: "\2718";
color: red;
}
.input-validation {
display: inline-block;
}
<input name="pw" autocomplete="off" type="text" id="pw" class="new" pattern="[a-zA-Z0-9]{6,22}" autofocus required/> <span class="input-validation"></span>

注意:

  • 我已将您的 CSS 选择器中的 ~ 替换为 +,因为 ~ 会选择所有与选择器匹配的兄弟,而 + 只选择相邻的兄弟。使用 ~ 将使所有输入框旁边的 span 在您输入第一个值时立即显示(当表单中有多个输入框时)。
  • 我还将 .input-validationdiv 修改为 span 但这更多是个人喜好,您可以保留原始 div 本身在功能上没有任何差异。

关于javascript - 加载/重新加载页面时隐藏验证输出标记 (✘) 符号隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17964904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com