使用 javascript 重置 html 所需的样式

Reset html required style with javascript

本文关键字:样式 html javascript 重置 使用      更新时间:2023-09-26

我有一个表单,其中包含一个输入,并设置了所需的属性。当我提交表单并且输入为空时,它周围显示一个红色边框。

我现在正在寻找一种 javascript 方法来删除它,并将输入的显示重置为初始状态。

重置并再次提交后,应再次检查输入,如果为空,则显示红色边框。因此,我认为使用 :required 设置 css 并不能提供所需的解决方案。

快速摆弄来说明我的问题:

jQuery(function() {
  jQuery('#reset').click(function() {
    //Clear red border of input
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
  <input id="myinput" required>
  <input type="submit" value="submit">
</form>
<button id="reset">reset</button>

单击重置后,表单应显示为刚刚加载页面时。

编辑我在火狐中对此进行了测试。在镶边中,当元素聚焦时,样式会自动删除。但是,我仍在寻找一种 js 解决方案来删除该消息。

编辑,更新

我想重置样式,而不是阻止它发生(当我不这样做时 专注于它(。

您可以向元素添加className #myinput该元素将box-shadow设置为noneborder设置为inherit #reset元素click。在元素上的focuschange事件#myinput删除className,确定是否要在无效输入时或在用户输入值时focus删除box-shadowborder

.reset:-moz-ui-invalid:not(output) {
  box-shadow: none;
  border: 1px solid inherit;
}

提交后,它会显示一条消息,例如"此字段为必填字段"。这 当我取消焦点时被删除,但我正在寻找一个 js 方法来删除 那条消息。

您可以使用invalid事件,.setCustomValidity(" ")将空格字符作为参数,在处理程序中event.target调用。


您可以使用 css :focus:invalidborder设置为仅在input获得焦点且输入无效时才red。在html可以添加pattern属性,如果输入的值为空字符串或仅空格字符,则可以RegExp 'w+input设置为无效

jQuery(document).ready(function() {
  jQuery("#reset").click(function() {
    jQuery("#myinput").addClass("reset")
  });
  jQuery("#myinput").focus(function() {
    jQuery(this).removeClass("reset")
  })
  .on("invalid", function(e) {
    e.target.setCustomValidity(" ");
  })
})
#myinput:focus:invalid {
  border: 1px solid red;
}
#myinput:focus {
  outline: none;
}
.reset:-moz-ui-invalid:not(output) {
  box-shadow: none;
  border: 1px solid inherit;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
  <input id="myinput" pattern="'w+" type="text" value="" required/>
  <input type="submit" value="submit" />
</form>
<button id="reset">reset</button>

我无法在这里重现它。但可能是您的问题是应用于输入的伪类。
鉴于您无法删除伪类,也许您可以覆盖样式。像这样:

:invalid {
  box-shadow: none;
}
:-moz-submit-invalid {
  box-shadow: none;
}
:-moz-ui-invalid {
  box-shadow:none;
}

如果只需要在单击重置按钮时应用样式,请将样式添加到您自己的类中,并在需要时添加/删除类。

initial 关键字使 CSS 属性采用浏览器的默认样式,如果这是您要查找的...

jQuery(function() {
  jQuery('#reset').click(function() {
    //Clear red border of input
    jQuery('#myinput').css('border-color', 'initial');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style type="text/css">
 #myinput {
  border-color: red;
 }
</style>
<form id="myform">
  <input id="myinput" required>
  <input type="submit" value="submit">
</form>
<button id="reset">reset</button>