如何在input [type ="number"]上使用模式? [英] How to use a pattern on an input[type="number"]?

查看:128
本文介绍了如何在input [type ="number"]上使用模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望默认值为0,如果输入大于0,则使用:valid重新着色.难道我做错了什么? Google Chrome浏览器是否错误?还是HTML5规范?我想在没有JS的情况下解决这个问题.

 :valid {
  background: green
} 

 <p>This should not be green, but it is:</p>
<input max="100" min="0" pattern="^[1-9]\d*$" type="number" value="0" />

<p>Works perfectly, if the type is changed to text:</p>
<input pattern="^[1-9]\d*$" type="text" value="0" /> 

解决方案

pattern属性上添加MDN (已突出显示):

模式

检查控件值的正则表达式. 模式必须与整个值匹配,而不仅仅是某些子集.使用 title属性描述模式以帮助用户. 此 当type属性的值为text时,此属性适用 搜索,电话,URL或电子邮件;否则将被忽略.常规 表达式语言与JavaScript相同.模式不是 被正斜杠包围.

有趣的是,在 W3C WhatWG 标准.

I want the default value to be 0 and recolor the input if it's more than 0, using :valid. Am I doing something wrong? Is Google Chrome wrong? Or the HTML5 specification? I want to solve this without JS.

:valid {
  background: green
}

<p>This should not be green, but it is:</p>
<input max="100" min="0" pattern="^[1-9]\d*$" type="number" value="0" />

<p>Works perfectly, if the type is changed to text:</p>
<input pattern="^[1-9]\d*$" type="text" value="0" />

解决方案

Citing MDN on the pattern property (highlighting added):

pattern

A regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored. The regular expression language is the same as JavaScript's. The pattern is not surrounded by forward slashes.

Interestingly I can't find any mentioning of that in both W3C and WhatWG standards.

这篇关于如何在input [type ="number"]上使用模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆