javascript - 如何更改纯 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>
解决方案
选择器中的 ID 不能以数字开头:
在 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 前加上一些字母。
推荐阅读
- automator - 如何在 Mojave 中修复 Automator 日期时间脚本
- angularjs - 如何使用 ng-repeat 获取 ckeditor 的实例?
- amp-html - 注册墙导致 AMP 验证问题
- python-3.x - python中的IP地址短列表
- c - C:在 1970 年之前的日期中添加天数,与操作系统无关
- java - Jersey FormDataBodyPart getValueAs 导致“实体实例不包含未转换的内容”。
- mongodb - 如何为 MongoDB 接收器的 Spark Structured Streaming 应用程序构建 uber jar
- c++ - 与 QProcess 和 VS C++ 进行实时通信时遇到问题
- php - 在 PHP 中删除/转换法语口音
- javascript - 如何仅在组件从 Firebase 接收数据后才映射StateToProps