哪些是“id”属性的有效值

id 属性定义了 HTML 元素的唯一标识符。

它在文档中必须是唯一的。
通常,它指向样式表中的样式、锚链接和脚本目标。

在这个片段中,我们将讨论 HTML、CSS 和 Javascript 的 id 属性的有效值。

语法

<tag id="id"></tag>

在 HTML4 中,id 属性的值必须以字母 (AZ, az) 开头,后面可以跟字母、数字 (0-9)、冒号 (:)、句点 (.)、连字符 (-) 和下划线(_)。

在 HTML5 中,id 属性必须是唯一的,至少包含一个字符且不应包含空格字符。

没有任何其他限制。

在 XHTML 中,id 属性区分大小写。

让我们看一个例子:

<tag id=":onitroad" ></tag>

其中id 属性的值在 HTML5 中是有效的。
但是,在 CSS 和 Javascript 中,标识符只能包含字母(A-Z、a-z)和数字(0-9)。

现在,我们将演示 HTML 和 CSS 中 id 属性的有效和无效值的示例。

CSS 中 id 属性的无效值示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      #1onitroad {
        color: #160987;
        font-size: 60px;
        font-weight: bold;
        text-align: center;
      }
      #2onitroad {
        text-align: center;
        font-size: 30px;
      }
    </style>
  </head>
  <body>
    <div id="1onitroad">onitroad</div>
    <div id="2onitroad">
      Learn programming
    </div>
  </body>
</html>

在上面的例子中,我们使用了两个 id 属性:1onitroad 和 2onitroad。
但是,使用 CSS 进行样式设置时,它们会提供简单的输出,因为这些值在 CSS 中无效。

在我们的下一个示例中,我们可以看到代码的样式结果,因为我们使用在 HTML 和 CSS 中都有效的值。

HTML5 和 CSS 中 id 属性的有效值示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      #onitroad {
        color: #160987;
        font-size: 60px;
        font-weight: bold;
        text-align: center;
      }
      #programming {
        text-align: center;
        font-size: 30px;
      }
    </style>
  </head>
  <body>
    <div id="onitroad">onitroad</div>
    <div id="programming">
      Learn programming
    </div>
  </body>
</html>

接下来,查看 HTML 和 JavaScript 中有效值和无效值的示例。

其中首先看一个值在 HTML5 中有效但在 Javascript 中无效的示例,然后是 HTML5 和 Javascript 都具有有效值的示例。

Javascript 中 id 属性的无效值示例:

<!DOCTYPE html>
<HTML>
  <head>
    <title>文档的标题</title>
    <style>
      #:w3dosc {
        color: #666;
      }
    </style>
  </head>
  <body>
    <h1 id=":onitroad">Example</h1>
    <button onclick="displayResult()">
      Click here
    </button>
    <script>
      function displayResult() {
        document.getElementById(
            ":w3dosc")
          .innerHTML = "Hello world!";
      }
    </script>
  </body>
</html>

如果我们单击上面示例中的“单击此处”按钮,则不会因为 JavaScript 的值无效而发生任何事情。

HTML5 和 Javascript 中 id 属性的有效值示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      #onitroad {
        color: #666;
      }
    </style>
  </head>
  <body>
    <h1 id="onitroad">Example</h1>
    <button onclick="displayResult()">
      Click here
    </button>
    <script>
      function displayResult() {
        document.getElementById(
            "onitroad")
          .innerHTML = "Hello world!";
      }
    </script>
  </body>
</html>
日期:2020-06-02 22:15:14 来源:oir作者:oir