为什么不一直简单地在 html/css 中使用 class 而不是 id?

use*_*486 1 html css

我读到id只能在 html 文档中使用一次,而class可以多次使用。既然如此,那程序员为什么不干脆一直用class呢?这不会让事情变得更简单吗?

Jac*_*ray 6

几个原因:

1: Id 用于定位一个元素,而类用于多个
示例:

<div id="test">This is red</div>
<div class="test"></div>
<div class="test"></div>

#test{
background:red;
}
Run Code Online (Sandbox Code Playgroud)

2: id 在 CSS 中的覆盖类
示例:

<div class="test" id="test">Test</div>
#test{ 
background:red;//Overrides, even though it is higher in the document
}
.test{
background:blue;
} 
Run Code Online (Sandbox Code Playgroud)

3: ID 用于 HTML 中的锚链接
示例:

<a href="#test">Link to test</a>
<div id="test"></div>
Run Code Online (Sandbox Code Playgroud)

4:使用 JavaScript 更容易选择 ID

<div id="test"></div>
<div class="test"></div>
document.getElementById("test"); //returns the element
document.getElementsByClassName("test"); //returns a HTMLCollection, which is like an array 
Run Code Online (Sandbox Code Playgroud)

  • 可能是数字 3 中的拼写错误(`href="#test"`) (2认同)