我可以有一个元素吗id
以数字开头或完全是数字?
例如。像这样的东西:
<div id="12"></div>
我可以有一个以 id 为数字的 div 吗?
是的你可以,但使用 CSS 选择器选择/设计它会很痛苦。
id
仅由数字组成的值在 HTML 中完全有效 http://www.w3.org/TR/html5/dom.html#the-id-attribute;除了空格之外的任何东西都可以。尽管早期的 HTML 规范更具限制性(ref http://www.w3.org/TR/html401/struct/global.html#adef-id, ref http://www.w3.org/TR/html401/types.html#type-name),需要一小组字符并以字母开头,浏览器从不关心,这也是 HTML5 规范开放的一个重要原因。
If你会用那些id
带有 CSS 选择器(例如,使用 CSS 设计它们的样式,或者使用querySelector
, querySelectorAll
,或者像 jQuery 这样使用 CSS 选择器的库),请注意这可能会很痛苦,你最好还是盯着id
带着一封信,因为你不能使用idCSS 中以数字开头id选择器字面上地 http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier;你必须逃避它。 (例如,#12
是无效的 CSS 选择器;你必须写它#\31\32
.) 因此,如果您打算将它与 CSS 选择器一起使用,那么以字母开头会更简单。
为了清楚起见,上面列出了这些链接:
- HTML5 - ID 属性 http://www.w3.org/TR/html5/dom.html#the-id-attribute
- HTML4 - ID 属性 http://www.w3.org/TR/html401/struct/global.html#adef-id and ID 和 NAME 令牌 http://www.w3.org/TR/html401/types.html#type-name
- CSS 2.1 ID 规则 http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
下面是一个使用的示例div
与id
“12”并以三种方式使用它:
- With CSS
- 使用 JavaScript 通过
document.getElementById
- 使用 JavaScript 通过
document.querySelector
(在支持它的浏览器上)
它适用于我曾经使用过的每个浏览器(请参阅代码下面的列表)。实例:
"use strict";
document.getElementById("12").style.border = "2px solid black";
if (document.querySelector) {
document.querySelector("#\\31\\32").style.fontStyle = "italic";
display("The font style is set using JavaScript with <code>document.querySelector</code>:");
display("document.querySelector(\"#\\\\31\\\\32\").style.fontStyle = \"italic\";", "pre");
} else {
display("(This browser doesn't support <code>document.querySelector</code>, so we couldn't try that.)");
}
function display(msg, tag) {
var elm = document.createElement(tag || 'p');
elm.innerHTML = String(msg);
document.body.appendChild(elm);
}
#\31\32 {
background: #0bf;
}
pre {
border: 1px solid #aaa;
background: #eee;
}
<div id="12">This div is: <code><div id="12">...</div></code>
</div>
<p>In the above:</p>
<p>The background is set using CSS:</p>
<pre>#\31\32 {
background: #0bf;
}</pre>
<p>(31 is the character code for 1 in hex; 32 is the character code for 2 in hex. You introduce those hex character sequences with the backslash, <a href="http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier">see the CSS spec</a>.)</p>
<p>The border is set from JavaScript using <code>document.getElementById</code>:</p>
<pre>document.getElementById("12").style.border = "2px solid black";</pre>
我从未见过上述在浏览器中失败的情况。这是一个subset我见过它可以在以下浏览器中使用:
- 铬 26、34、39
- IE6、IE8、IE9、IE10、IE11
- 火狐浏览器 3.6、20、29
- IE10(移动版)
- Safari iOS 3.1.2、iOS 7
- 安卓2.3.6、4.2
- 歌剧 10.62、12.15、20
- 征服者 4.7.4
但再说一遍:If你要对元素使用 CSS 选择器,最好以字母开头;选择器喜欢#\31\32
读起来非常困难。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)