gpt4 book ai didi

javascript - 为什么不能通过 JavaScript 在 'style' 属性中插入分号?

转载 作者:搜寻专家 更新时间:2023-10-31 08:15:14 25 4
gpt4 key购买 nike

我试图用 JavaScript 更改 body 的背景颜色,发现以下内容不起作用:

document.body.style.background = "#000;"

但是,如果我省略分号,它就可以工作了:

document.body.style.background = "#000"

为什么会这样? #000; 不还是字符串吗?

最佳答案

; 不是值的一部分。这是一个样式分隔符

selector {
styleName: styleValue;
/* Separator --------^----- */
}

来自 the specification :

A rule set (also called "rule") consists of a selector followed by a declaration block.

A declaration block starts with a left curly brace ({) and ends with the matching right curly brace (}). In between there must be a list of zero or more semicolon-separated (;) declarations.

您的第二个示例(没有 ;)是正确的。您的第一个示例无法设置样式,因为值 #000; 无效,因此浏览器会忽略它。

关于javascript - 为什么不能通过 JavaScript 在 'style' 属性中插入分号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40438205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com