首页 > 解决方案 > 如何更改纯 CSS JS 中的 ID?为什么我的代码不起作用?

问题描述

这段代码不起作用,尽管它对我来说似乎是正确的。你能告诉我有什么问题吗?

<style>
    #101{
        width:1em;
        height:1em;
        padding:1em;
        margin: 1em;
        background-color: green;
        color:red;
    }
</style>
<div class="animation" id="animation">hii</div>
<script>
    document.getElementById('animation').id='101';
</script>

标签: javascripthtmlcss

解决方案


选择器中的 ID 不能以数字开头:

4.1.3 字符和大小写

在 CSS 中,标识符(包括选择器中的元素名称、类和 ID)只能包含字符 [a-zA-Z0-9] 和 ISO 10646 字符 U+00A0 及更高,加上连字符 (-) 和下划线 ( _); 它们不能以数字、两个连字符或一个连字符后跟一个数字开头。标识符还可以包含转义字符和任何 ISO 10646 字符作为数字代码(请参阅下一项)。例如,标识符“B&W?” 可以写成“B\&W\?” 或“B\26 W\3F”。

您可以通过编写这样的选择器来解决这个问题#\31 01,但这并不是真正推荐的(31是字符的十六进制表示1):

<style>
     #\31 01{
        width:1em;
        height:1em;
        padding:1em;
        margin: 1em;
        background-color: green;
        color:red;
    }
</style>
<div class="animation" id="animation">hii</div>
<script>
    document.getElementById('animation').id='101';
</script>

所以最好在 ID 前加上一些字母。


推荐阅读