简体   繁体   中英

Why can't a semicolon be inserted through JavaScript in a 'style' attribute?

I was trying to change the background colour of body with JavaScript and observed that the following doesn't work:

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

But if I omit the semicolon then it works:

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

Why is it so? Isn't #000; still a string?

; isn't part of the value. It's a style separator .

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

From 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.

Your second example (without the ; ) is correct. Your first example fails to set the style because the value #000; is invalid, so the browser ignores it.

Because when you set background style to #000 , it outputs background: #000 . This is not a proper CSS rule.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM