简体   繁体   中英

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.

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.

$('#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".

在此处输入图片说明

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. 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. 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';

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