html5表单属性

tech2022-11-06  99

html5表单属性

The following is an extract from our book, HTML5 & CSS3 for the Real World, 2nd Edition, written by Alexis Goldstein, Louis Lazaris, and Estelle Weyl. Copies are sold in stores worldwide, or you can buy it in ebook form here.

以下摘自Alexis Goldstein,Louis Lazaris和Estelle Weyl编写的《现实世界HTML5和CSS3,第二版 》一书。 副本在世界各地的商店中都有出售,您也可以在这里以电子书的形式购买。

required属性 (The required Attribute)

The Boolean required attribute tells the browser to only submit the form if the field in question is filled out. Obviously, this means that the field can’t be left empty, but it also means that, depending on other attributes or the field’s type, only certain types of values will be accepted. Later in the chapter, we’ll be covering different ways of letting browsers know what kind of data is expected in a form.

布尔值required属性告诉浏览器仅在填写有问题的字段时提交表单。 显然,这意味着该字段不能为空,但这还意味着,根据其他属性或字段的类型,将仅接受某些类型的值。 在本章的后面,我们将介绍让浏览器知道某种形式的数据的不同方式。

If a required field is empty the form will fail to submit. Opera, Firefox, Internet Explorer 10+, and Chrome provide the user with error messages; for example, “Please fill out this field” or “You have to specify a value” if left empty.

如果必填字段为空,则表单将无法提交。 Opera,Firefox,Internet Explorer 10+和Chrome为用户提供错误消息; 例如,如果留空,则“请填写此字段”或“您必须指定一个值”。

注意:时间集中 (Note: Time to Focus)

Time for a quick refresher: a form element is focused either when users click on the field with their mouse, tap into the field with their finger on a touch device, tab to it with their keyboard, or click or touches the label associated with that form element. For input elements, typing with the keyboard will enter data into that element.

快速刷新的时间:当用户用鼠标单击该字段,用手指在触摸设备上点击该字段,用键盘将其制表符或单击或触摸与该设备相关联的标签时,表单元素将被聚焦表单元素。 对于输入元素,使用键盘键入会将数据输入该元素。

In JavaScript focus event terminology, the focusevent will fire on a form element when it receives focus, and the blur event will fire when it losesfocus.

在JavaScript focus事件术语中, focus事件将在收到焦点时在表单元素上触发,而blur事件在失去焦点时将触发。

In CSS, the :focus pseudo-class can be used to style elements that currently have focus.

在CSS中, :focus伪类可用于设置当前具有焦点的元素的样式。

The required attribute is valid on any input type except button,submit, image, range, color, and hidden, all of which generally have a default value so the attribute would be redundant. As with other Boolean attributes we’ve seen so far, the syntax is either simply required, or required="required" if you’re using XHTML syntax.

required属性在除button , submit , image , range , color和hidden之外的任何输入类型上均有效,所有这些通常具有默认值,因此该属性将是多余的。 与到目前为止我们看到的其他布尔属性一样,该语法只是required ,或者,如果您使用的是XHTML语法,则它是required="required" 。

Let’s add the required attribute to our sign-up form. We’ll make the name, email address, password, and subscription start date fields required:

让我们将required属性添加到我们的注册表单中。 我们将需要输入姓名,电子邮件地址,密码和订阅开始日期字段:

<ul> <li> <label for="register-name">My name is:</label> <input type="text" id="register-name" name="name" required aria- ↵required="true"> </li> <li> <label for="email">My email address is:</label> <input type="text" id="email" name="email" required aria- ↵required="true"> </li> <li> <label for="url">My website is located at:</label> <input type="text" id="url" name="url"> </li> <li> <label for="password">I would like my password to be:</label> <p>(at least 6 characters, no spaces)</p> <input type="password" id="password" name="password" required ↵aria-required="true"> </li> <li> <label for="rating">On a scale of 1 to 10, my knowledge of ↵HTML5 is:</label> <input type="text" name="rating" type="range"> </li> <li> <label for="startdate">Please start my subscription on: ↵</label> <input type="text" id="startdate" name="startdate" required aria ↵-required="true"> </li> <li> <label for="quantity">I would like to receive <input ↵type="text" name="quantity" id="quantity"> copies of <cite> ↵The HTML5 Herald</cite></label> </li> <li> <label for="upsell">Also sign me up for <cite>The CSS3 ↵Chronicle</cite></label> <input type="checkbox" id="upsell" name="upsell" ↵value="CSS Chronicle"> </li> <li> <input type="submit" id="register-submit" value="Send Post ↵Haste"> </li> </ul>

注意:改善可访问性 (Note: Improving Accessibility)

You can include the WAI-ARIA attribute aria-required="true" for improved accessibility; however, as most browsers and screen readers now natively support the required attribute, this will soon by unnecessary. See Appendix B for a brief introduction to WAI-ARIA.

您可以包括WAI-ARIA属性aria-required="true"以改善可访问性; 但是,由于大多数浏览器和屏幕阅读器现在都固有地支持required属性,因此很快将不再required此属性。 有关WAI-ARIA的简要介绍,请参见附录B。

Figure 4.1, Figure 4.2, and Figure 4.3 show the behavior of the required attribute when you attempt to submit the form.

图4.1,图4.2和图4.3显示了尝试提交表单时required属性的行为。

Figure 4.1. The required field validation message in Firefox

图4.1。 Firefox中的必填字段验证消息

Figure 4.2. How it looks in Opera …

图4.2。 在Opera中的外观...

Figure 4.3. … and in Google Chrome

图4.3。 …以及在Google Chrome中

样式化所需表单字段 (Styling Required Form Fields)

You can style required form elements with the :required pseudo-class, and optional form elements with the :optional pseudo-class (or use the negation pseudo-class :not(:required)). You can also style valid and invalid fields with the :valid and:invalid pseudo-classes respectively. With these pseudo-classes and a little CSS magic, you provide visual cues to sighted users indicating which fields are required, and give feedback for successful data entry:

您可以使用:required伪类为必需的表单元素设置样式,并使用:optional伪类为可选的表单元素设置样式(或使用否定伪类:not(:required) )。 您也可以分别使用:valid和:invalid伪类设置有效和无效字段的样式。 通过这些伪类和一点CSS魔术,您可以为有视力的用户提供视觉提示,指示需要哪些字段,并提供成功输入数据的反馈:

input { background-position: 0% 50%; background-repeat: no-repeat; padding-left: 15px; } input:required { background-image: url('../images/required.png'); } input:focus:invalid { background-image: url('../images/invalid.png'); } input:focus:valid { background-image: url('../images/valid.png'); }

We’re adding a background image (an asterisk) to required form fields. We can’t include generated content on an input as they’re replaced or empty elements, so we use a background image instead. We’ve also added separate background images to valid and invalid fields. The change is only apparent when the form element has focus, to keep the form from looking too cluttered.

我们正在将背景图片(星号)添加到必填表单字段中。 由于生成的内容已被替换或为空元素,因此无法在input包括这些内容,因此我们使用背景图像代替。 我们还为有效和无效字段添加了单独的背景图片。 仅当表单元素具有焦点时才可以看到更改,以防止表单看起来过于混乱。

警告:Firefox将样式应用于无效元素 (Warning: Firefox Applies Styles to Invalid Elements)

Note that Firefox applies its own styles to invalid elements (a red shadow), as shown in Figure 4.1 earlier. You may want to remove the native drop shadow with the following CSS:

请注意,Firefox将自己的样式应用于无效元素(红色阴影),如前面的图4.1所示。 您可能要使用以下CSS删除本机投影:

:invalid { box-shadow: none; }

提示:旧版浏览器的目标样式 (Tip: Targeted Styles for Older Browsers)

Older browsers such as IE8 and IE9 don’t support the :required pseudo-class, but you can still provide targeted styles using the attribute selector:

较旧的浏览器,例如IE8和IE9不支持:required伪类,但是您仍然可以使用属性选择器提供目标样式:

input:required, input[required] { background-image: url('../images/required.png'); }

You can also use this attribute as a hook for form validation in browsers without support for HTML5 form validation. Your JavaScript code can check for the presence of the required attribute on value-less inputs, and not submit the form if any are found.

您也可以将此属性用作在不支持HTML5表单验证的浏览器中进行表单验证的钩子。 您JavaScript代码可以检查无值输入中是否存在required属性,如果发现表单,则不提交表单。

placeholder属性 (The placeholder Attribute)

The placeholder attribute allows a short hint to be displayed inside the form element—space permitting—telling the user what type of data should be entered in that field. The placeholder text disappears when the field gains focus and the user enters at least one character, and reappears when the value is null. Developers have provided similar functionality with JavaScript for years―adding a temporary value, then clearing the value on focus―but in HTML5 the placeholder attribute allows it to happen natively with no JavaScript required, and stays present until a value is entered.

placeholder属性允许在表单元素内显示简短提示(如果允许的话),告诉用户应在该字段中输入什么类型的数据。 当该字段获得焦点并且用户输入至少一个字符时,占位符文本消失,而当该值为null时,占位符文本再次出现。 多年来,开发人员已经提供了与JavaScript类似的功能-添加一个临时值,然后清除该焦点值-但在HTML5中,占位符属性允许它在不需要JavaScript的情况下自然发生,并且一直存在直到输入值为止。

For The HTML5 Herald’s sign-up form, we’ll put a placeholder on the website URL and start date fields:

对于HTML5 Herald的注册表单,我们将在网站URL和开始日期字段中放置一个placeholder :

<li> <label for="url">My website is located at:</label> <input type="text" id="url" name="url" ↵ placeholder="e.g. http://example.com"> </li> … <li> <label for="startdate">Please start my subscription on:</label> <input type="text" id="startdate" name="startdate" required ↵aria-required="true" > </li>

In Internet Explorer, because the placeholder attribute only received support in IE10, and because the placeholder text disappears once the user enters data, you shouldn’t rely on it as the only way to inform users of requirements. If your hint exceeds the size of the field, describe the requirements in the input’s title attribute, in the label or in text next to the input element. Some developers suggest adding “e.g.” as part of the placeholder text to make it evident that it’s placeholder text and not actually prefilled data.

在Internet Explorer中,由于placeholder属性仅在IE10中得到支持,并且由于占位符文本在用户输入数据后消失,因此不应将其作为通知用户需求的唯一方法。 如果您的提示超出了字段的大小,请在输入的title属性,标签或输入元素旁边的文本中描述要求。 一些开发人员建议在占位符文本中添加“例如”,以表明它是占位符文本,而不是实际上预填充的数据。

All browsers starting with Safari 4, Chrome 10, Opera 11.1, Firefox 4, Android 2.3, and Internet Explorer 10 support the placeholder attribute, though the original implementation ofplaceholder removed the placeholder text on focus rather than on data entry.

所有以Safari 4,Chrome 10,Opera 11.1,Firefox 4,Android 2.3和Internet Explorer 10开头的浏览器都支持placeholder属性,尽管placeholder的原始实现将placeholder符文本移到了焦点而不是数据输入上。

JavaScript的Polyfilling支持 (Polyfilling Support with JavaScript)

Like everything else in this chapter, it won’t hurt to include theplaceholder attribute even when dealing with older browsers that lack support.

像本章中的其他所有内容一样,即使在处理缺少支持的较旧的浏览器时,包含placeholder属性也不会受到损害。

As with the required attribute, you can make use of theplaceholder attribute and its value to make older versions of Internet Explorer behave as if they supported it—all by using a little JavaScript polyfill magic.

与required属性一样,您可以使用placeholder属性及其值使旧版本的Internet Explorer表现得好像它们支持它一样-都可以使用一点JavaScript polyfill魔术。

Here’s how you’d go about it: first, use JavaScript to determine which browsers are without support. Then, in those browsers, use a function that creates a faux placeholder. The function needs to determine which form fields contain the placeholderattribute, then temporarily grab that attribute’s content and replace empty value attributes with that text.

解决方法如下:首先,使用JavaScript确定哪些浏览器不受支持。 然后,在这些浏览器中,使用创建伪占位符的函数。 该函数需要确定哪些表单字段包含placeholder属性,然后临时获取该属性的内容并将空值属性替换为该文本。

Then you need to set up two event handlers: one to clear the field’s value on focus, and another to replace the placeholdervalue on blur if the form control’s value is still an empty string. If you do use this trick, make sure that the value of your placeholder attribute isn’t one that users might actually enter, or alternatively use the “e.g.” precursor to indicate that the placeholder is an example and not a valid value. Additionally, remember to clear the faux placeholder when the form is submitted. Otherwise, you’ll have lots of “(XXX) XXX-XXXX” submissions!

然后,您需要设置两个事件处理程序:一个用于清除焦点上的字段的值,另一个用于如果表单控件的值仍为空字符串则在模糊时替换placeholder值。 如果您确实使用了这种技巧,请确保您的占位符属性的值不是用户可能实际输入的值,或者使用“ eg”前体表示占位符是示例,而不是有效值。 此外,请记住在提交表单时清除人造占位符。 否则,您将有很多“(XXX)XXX-XXXX”提交!

Let’s look at a sample JavaScript snippet to progressively enhance our form elements using the placeholder attribute.

让我们看一个示例JavaScript代码段,以使用placeholder属性逐步增强表单元素。

Here’s our placeholder polyfill:

这是我们的占位符polyfill:

<script> // check if supported if(!Modernizr.input.placeholder) { // get all the form controls with the placeholder attribute var fcToCheck = document.querySelectorAll("*[placeholder]"), frmsToCheck = document.querySelectorAll('form'), i, count; // loop through form controls with placeholder attribute, // copy placeholder value into value, clearing on focus and // resetting, if empty, on blur for(var i = 0, count = fcToCheck.length; i < count; i++) { if(fcToCheck[i].value == "") { fcToCheck[i].value = fcToCheck[i].getAttribute("placeholder"); fcToCheck[i].classList.add('placeholder'); fcToCheck[i].addEventListener('focus', function() { if (this.value==this.getAttribute("placeholder")) { this.value = ''; this.classList.remove('placeholder'); } }); fcToCheck[i].addEventListener('blur', function() { if (this.value == '') { this.value = this.getAttribute("placeholder"); this.classList.add('placeholder'); } }); } } for(i = 0, count = frmsToCheck.length; i < count; i++) { frmsToCheck[i].addEventListener('submit', function(e) { var i, count, plcHld; // first do all the checking for required // element and form validation. // Only remove placeholders before final submission plcHld = this.querySelectorAll('[placeholder]'); for(i = 0, count = plcHld.length; i < count; i++){ //if the placeholder still equals the value if(plcHld[i].value == plcHld[i].getAttribute( ↵'placeholder')){ // don't submit if required if(plcHld[i].hasAttribute('required')) { // create error messaging plcHld[i].classList.add('error'); e.preventDefault(); } else { // if not required, clear value before submitting. plcHld[i].value = ''; } } else { // remove legacy error messaging plcHld[i].classList.remove('error'); } } }); } </script>

The first point to note about this script is that we’re using theModernizr JavaScript library to detect support for the placeholderattribute. There’s more information about Modernizr in Appendix A, but for now it’s enough to understand that it provides you with a whole raft of true or false properties for the presence of given HTML5 and CSS3 features in the browser. In this case, the property we’re using is fairly self-explanatory.Modernizr.input.placeholder will be true if the browser supportsplaceholder, and false if it doesn’t.

关于此脚本的第一点注意事项是,我们正在使用Modernizr JavaScript库来检测对placeholder属性的支持。 附录A中提供了有关Modernizr的更多信息,但到目前为止,您已经足够了解它为浏览器中存在给定HTML5和CSS3功能提供了很多true或false属性。 在这种情况下,我们使用的属性是不言自明的。 如果浏览器支持placeholder ,则Modernizr.input.placeholder将为true否则,则为false 。

If we’ve determined that placeholder support is absent, we grab all the elements on the page with a placeholder attribute. For each of them, we check that the value isn’t empty, then replace that value with the value of the placeholder attribute. In the process, we add the placeholder class to the element, so you can lighten the color of the font in your CSS or otherwise make it look more like a native placeholder. When the user focuses on the input with the faux placeholder, the script clears the value and removes the class. When the user removes focus, the script checks to see if there is a value. If not, we add the placeholder text and class back in.

如果我们确定不存在placeholder支持,则使用placeholder属性获取页面上的所有元素。 对于它们中的每一个,我们检查该值是否为空,然后用placeholder属性的值替换该值。 在此过程中,我们将placeholder类添加到元素,以便您可以减轻CSS中字体的颜色,或者使其看起来更像本机占位符。 当用户将重点放在带有人造占位符的输入上时,脚本将清除该值并删除该类。 当用户移开焦点时,脚本将检查是否有值。 如果没有,我们添加占位符文本和类。

Before submitting the form, we need to check if any form controls have a value that matches their placeholder attribute. In this scenario, we could have also checked to see whether any required input still has the placeholder class when the form is submitted. If a form control is required, we add error messaging and prevent the form from submitting. If the form control isn’t required, we clear the placeholder values that are still in place before submitting, only clearing those if no required elements have prevented form submission.

在提交表单之前,我们需要检查是否有任何表单控件的值与其placeholder属性相匹配。 在这种情况下,我们还可以检查提交表单时是否还需要任何placeholder类。 如果需要表单控件,我们将添加错误消息并阻止表单提交。 如果不需要表单控件,我们将在提交之前清除仍保留的占位符值,仅在没有必需元素阻止表单提交时清除这些值。

Before adding a reset button to your form, determine whether your users will ever want to throw away all of their work. If the answer is yes and you include a reset button, note that if the user clicks on the reset button, our faux placeholders will disappear but the placeholder class will remain, as we are using the value in our polyfill.

在将重设按钮添加到表单之前,请确定您的用户是否曾经想放弃所有工作。 如果答案是肯定的,并且您包含一个重置按钮,请注意,如果用户单击重置按钮,我们的人造占位符将消失,但placeholder类将保留,因为我们正在使用polyfill中的值。

This is a great example of an HTML5 polyfill: we use JavaScript to provide support only for those browsers without native support, and we do it by leveraging the HTML5 elements and attributes already in place, rather than resorting to additional classes or hard-coded values in our JavaScript.

这是HTML5 polyfill的一个很好的例子:我们使用JavaScript仅为那些没有本机支持的浏览器提供支持,而我们通过利用已经存在HTML5元素和属性来做到这一点,而不是求助于其他类或硬编码值在我们JavaScript中。

While the placeholder attribute may not be the most important one to polyfill, it’s a good example of how we can simplify form validation scripts while polyfilling support for all the new attributes, all while maintaining separation between the content and presentation layers.

尽管placeholder属性可能不是最重要的Polyfill,但它是一个很好的例子,说明了我们可以简化表单验证脚本,同时对所有新属性进行Polyfill支持,同时又保持内容层和表示层之间的分隔。

翻译自: https://www.sitepoint.com/html5-form-attributes-part-1/

html5表单属性

最新回复(0)