简体   繁体   中英

Styling span textnode without styling child nodes

So I'm creating a theme plugin for a forum where users often enter text with custom coloring. This is implemented as an inline style on a span.

The forum by default has a dark color scheme so most of the text is light. If I create a theme with a light color scheme this text would be hard to see.

I thought of using a CSS5 color filter that targets text with inline colors:

.Comment span[style^=color] {
   filter: hue-rotate(180deg) invert(100%);
   -webkit-filter: hue-rotate(180deg) invert(100%);
}

By inverting and rotating the color spectrum this turns a light blue color into a dark blue and light red into dark red, preserving the hue but making it darker. This actually works but it has the side effect of also inverting the colors of images and other elements embedded in the text.

I thought of doing another color inversion on child elements but this leaves images looking like junk since apparently hue-rotate is not very accurate at all.

A solution would be to have the CSS only target the text node of the span and not any child elements but that does not seem possible? Unless I'm missing something I don't see any selectors for text nodes.

Is there something I can do in jQuery to perform this color inversion? I'd rather not have to destroy all the coloring on the page as that would upset the users.

this Solution only goes lighter does not solve the problem:

I mis-read the question... I tried to delete this because it did not solve the problem for light backgrounds but it still appeared.

This can be accomplished by making use of rgba

Tested and works:

$(window).load(function() {
      var col = $('.Comment').css('color').replace(')', ', 0.20)').replace('rgb', 'rgba');
      $('.Comment').css('color', col);    
});     

var col converts rgb to rgba allowing for color percentage

Here's a solution that uses the javascript library tinycolor. A pure CSS solution would be much preferred but it doesn't seem possible.

$.getScript('https://rawgit.com/bgrins/TinyColor/master/tinycolor.js').done( function() {
    $('.Comment span[style^=color]').each(function() {
        var color = tinycolor($(this).css('color')).toHsl();
        color.l = 1 - color.l;
        $(this).css({'color': tinycolor(color).toRgbString()});
    });
});

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