HTML Boolean Attributes_html/css_WEB

lxf2023-03-25 14:08:02

有时读别人的 HTML 写代码时,会发现在写 / /

几天前,我突然发现我没有弄清楚 HTML 如果布尔属性有价值,哪些是合法价值,我觉得其实是什么? 字符串和 "false"表示 假值,然后看看规范才明白不是这样。

HTML 布尔属性(Boolean attributes)

HTML5 规范说:

… 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.

所以,如果要表达的话 选定的写法有:

如果说不选中,就不能出现 checked:

个人不同意空字符串可以作为合法价值,感觉会给人一种不选择的误导。

checked和 checked="checked"区别

在 W3C 的 HTML 4.01 已经有规范了 Boolean attributes 说明中提到:

Authors should be aware that many user agents only recognize the minimized form of boolean attributes and not the full form.

当然,现在主流浏览器都支持 checked="checked“这种写法,所以实际使用效果没有区别。

主要区别在于: checked字符少,简洁直观;而且使用起来; checked="checked主要原因是“ XHTML 中,只写 checked不合法,但我们通常是在写作 HTML5,所以没有理由写, checked="checked"。

布尔属性(Boolean attributes)列表

这篇文章的写作时有发生 39 个:

allowFullscreenasyncautofocusautoplaycheckedcompactcontrolsdeclaredefaultdefaultCheckeddefaultMuteddefaultSelecteddeferdisableddraggableenabledformNoValidatehiddenimageSmoothingEnabledindeterminateisMaploopmultiplemutednoHrefnoResizenoShadenoValidatenoWrapopenpauseOnExitreadOnlyrequiredreversedselectedspellchecktranslatetrueSpeedtypeMustMatch

以上列表获取方法:WHATWG HTML 规范在 Github 上面的仓库( https://github.com/whatwg/html)

git clone https://github.com/whatwg/htmlcd html# cat source | grep "attribute boolean" 手工处理后,或执行下面的代码catcat source | grep "attribute boolean" | grep -v "readonly attribute boolean" | grep -oE "\">[A-Za-z]{1,}" | awk -F'>|<' '{print $2}' | sort | uniq<' '{print $2}' | sort | uniq

Boolean attributes in React

React JSX 语法与 HTML 不一样,在 JSX 中间,可以传入 true表示设置布尔属性,传入布尔属性 false表示不设置此属性,如:

表示选择复选框:

表示不选择复选框: