简体   繁体   English

使用Javascript修改CSS类无效

[英]Modify css class with Javascript doesn't work

I'm currently writing a little chrome extension to modify an existing site. 我目前正在编写一个chrome扩展程序来修改现有网站。 I try to modify one div element if the child contains an attribute with the value (for example red, blue, ...). 如果子级包含具有值的属性(例如红色,蓝色,...),则尝试修改一个div元素。 If the child contains a value with the attribute value red I want the parent div colored in red and so on. 如果子级包含一个属性值为红色的值,则我希望父级div着色为红色,依此类推。

I've worte this JS: 我已经把这个JS弄糟了:

//find the parent div element
element = element.getElementsByClassName("existing-class-to-find-div")[0];
// check if the attribute from the child is blue
...
if (color == blue){
   element.className += " RedColorClass";
}

if I printout the elmenent with element.outerHTML or the className everything is fine and I see the new value. 如果我用element.outerHTML或className打印出元素,一切都很好,我会看到新值。 BUT on the actual site there is still the old value and it isn't changed. 但是在实际站点上仍然有旧值,并且它没有更改。 Do I have to trigger something to refresh the html site or so? 我是否必须触发一些刷新HTML网站的内容?

使用element.classList.add("RedColorClass")或者,如果使用jQuery:

 $(element).addClass("RedColorClass");

If doing this without a lib, the style sheet object might be a better target to modify. 如果在没有lib的情况下执行此操作,则样式表对象可能是更好的修改目标。

The this I am assuming is changing the background to red for the class .existing-class-to-find-div, based on comments. 我假设这是根据注释将类.existing-class-to-find-div的背景更改为红色。 It is best to move that info into the question. 最好将这些信息放入问题中。

The style sheet itself is a different object. 样式表本身是一个不同的对象。

var CSSStyleSheet = document.styleSheets[0]; /*danger this is first style sheet not necessarily the correct sheet */
CSSStyleSheet.addRule(".existing-class-to-find-div", "background-color:red");

The source code of the style sheet will not be changed, but the devtools should show the change. 样式表的源代码不会更改,但是devtools应该显示更改。

On the code which is pasted vars color and blue are not defined. 在粘贴的代码中,未定义变色和蓝色。 I suspect that is where the problem is. 我怀疑这就是问题所在。

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

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