Html 的布尔属性

Boolean Attributes Of Html

当我使用 html 属性时,我看到了布尔属性并且我已经使用了很多次。

但是当我去mdn docs to boolean attributes的时候,我读到布尔属性只能有一个值,通常与属性名称相同。

而且正如我们所知,布尔属性可以在没有值的情况下写入。 但是当我做一些实验时,我看到了奇怪的行为

<input type="text" disabled />

这是一个输入 elemnet,它具有没有值的布尔属性,并且可以正常工作。

<input type="text" disabled="disabled" />

这是一个输入 elemnet,它具有布尔属性,其值与它们的名称相同,而且它也如预期的那样正常工作。

<input type="text" disabled="anything" />

这里是一个具有布尔属性的输入元素,它具有任何值并且可以正常工作。

为什么具有任何值的布尔属性都能正常工作?

检查 HTML standard 是否有任何语法问题。引用它:

A number of attributes are boolean attributes. The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.

Here is an example of a checkbox that is checked and disabled. The checked and disabled attributes are the boolean attributes.

<label><input type=checkbox checked name=cheese disabled> Cheese</label>

This could be equivalently written as this:

<label><input type=checkbox checked=checked name=cheese disabled=disabled> Cheese</label>

You can also mix styles; the following is still equivalent:

<label><input type='checkbox' checked name=cheese disabled=""> Cheese</label>

why boolean attribute that has anything as value works correctly?

浏览器有 大量 错误处理例程用于从无效 HTML.

中恢复

这就是其中之一。