简体   繁体   English

为什么我不能使用JavaScript在Chrome中直接分配给element.style?

[英]Why can't I directly assign to element.style in Chrome using JavaScript?

Quick question... for some reason, when I run the following in Chrome (or Safari) on my "li" tags: 快速提问...由于某种原因,当我在Chrome(或Safari)的“ li”标签上运行以下命令时:

myListElement.style.backgroundColor="red";

It works. 有用。 Yet when I try the following: 但是,当我尝试以下操作时:

myListElement.style="li{background:red;}";

It doesn't. 没有。 However, it works in Firefox. 但是,它可以在Firefox中使用。 Does anyone know why this is? 有人知道为什么是这样吗? I've resorted to using the latter method because when I do the first method it overrides the :hover styling I have assigned to my elements. 我求助于使用后一种方法,因为当我执行第一种方法时,它会覆盖我已分配给元素的:hover样式。 Otherwise, I'd be using the first method. 否则,我将使用第一种方法。 Any help is appreciated. 任何帮助表示赞赏。 Thanks guys! 多谢你们!

If you check out the style attribute associated with DOM elements, you'll see that, at least in Chrome, it's actually a CSSStyleDeclaration object -- which is why changing it to a string doesn't work. 如果您检查与DOM元素关联的style属性,至少在Chrome中,它实际上是一个CSSStyleDeclaration对象-这就是为什么将其更改为字符串无效的原因。 One of its attributes is backgroundColor , and that is a string which you can simply modify. 它的属性之一是backgroundColor是一个您可以简单修改的​​字符串。 Hope this helps! 希望这可以帮助!

怎么样:

myListElement.setAttribute("style", "background:red;");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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