简体   繁体   English

jQuery动态背景色更改迫使包含该类的元素采用“内联”样式

[英]jQuery dynamic background-color change is forcing “inline” style on elements that contain the class

Sup dudes, 伙计们,

So... here's a weird prob. 所以...这是一个奇怪的问题。 The goal is to dynamically set the background-color of a class, using a color picker, where certain "div" element(s) may or may not contain that class. 目标是使用颜色选择器动态设置类的背景色 ,其中某些“ div”元素可能包含也可能不包含该类。

The following code "kind of" works, however, elements that contain the class, (where the background-color is being changed), is for some reason changing the background-color via "inline-style". 以下代码“种类”有效,但是,包含类的元素(正在更改背景色)由于某种原因通过“内联样式”更改了背景色。 (Which makes the whole thing not work) I've tried !important and a few other things with little success. (这使整个事情不起作用)我已经尝试过!重要的和其他一些事情,但收效甚微。 Any ideas? 有任何想法吗?

Note: .secondaryB is the class with the problem. 注意: .secondaryB是有问题的类。

$('#colorSelector4').ColorPicker({

    onChange: function (hsb, hex, rgb) {
        $('#colorSelector4 div').css('background-color', '#' + hex);
        $('.secondaryColor').css('color', '#' + hex);
        $('.secondaryColorB').css('background-color', '');
        $('.secondaryColorB').css('background-color', '#' + hex);
    }

});

Note: Here's what is happening in the Chrome console to elements that contain ".secondaryB". 注意:以下是Chrome控制台中包含“ .secondaryB”的元素所发生的事情。

在此处输入图片说明

Because you are applying styles directly to elements, you are using the style property on those elements and this can only translate into inline styles. 因为您直接将样式应用于元素,所以您在这些元素上使用了style属性,这只能转换为嵌入式样式。 There are ways of dynamically creating stylesheets however, as described here . 但是,有一些方法可以动态创建样式表,如此处所述

Given a reference to a stylesheet (eg from the document.styleSheets array), and a reference to the specific rule you want to change (via the stylesheet.cssRules array), you can set its style property and it will modify the stylesheet itself, instead of the inline styles. 给定对样式表的引用(例如,来自document.styleSheets数组),以及对要更改的特定规则的引用(通过stylesheet.cssRules数组),则可以设置其style属性,它将修改样式表本身,而不是内联样式。 Example: 例:

// Assuming that the rule you want is the first rule of the first stylesheet of the page
document.styleSheets[0].cssRules[0].style.backgroundColor = 'blue';

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

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