Combine the properties of two CSS classes with a filter attribute

后端 未结 1 702
长发绾君心
长发绾君心 2021-01-26 10:15

To sum up the effects of the filter property we have to do as for this \'union class.\'

.class1{filter:brightness(125%);}
.class2{filter:blur(5px);}
.unionClass{         


        
1条回答
  •  北恋
    北恋 (楼主)
    2021-01-26 11:10

    That is not possible to do using CSS.

    When splitt'd like that, the latter will overwrite the former, as it will with any other property.

    From a maintenance and easy-to-read perspective it could be interesting to do something like this

    .fil-bright-125 {
      filter:brightness(125%);
    }
    
    .fil-blur-5 {
      filter:blur(5px);
    }
    
    .fil-bright-125.fil-blur-5 {
      filter:brightness(125%) blur(5px);
    }
    

    And then use it like this

    p {
      color: blue;
      background: yellow;
    }
    
    .fil-bright-175 {
      filter:brightness(175%);
    }
    
    .fil-blur-1 {
      filter:blur(1px);
    }
    
    .fil-bright-175.fil-blur-1 {
      filter:brightness(175%) blur(1px);
    }

    I am bright

    I am blurry

    I am bright and blurry


    Updated

    For completeness, here is a version using script, which look up the classes in the style sheet and then creates a new, where they are combined.

    Compared with the above, I don't find the below more maintainable, almost the opposite actually.

    Note, this script can of course be optimized, though the purpose was to show a sample of how it could be done using script

    (function(d, w) {
      w.addEventListener("load", function() {
    
        function getStyle(cls) {
          var classes = d.styleSheets[0].rules || d.styleSheets[0].cssRules;
          var val = '';
          for (var x = 0; x < classes.length; x++) {
            for (var y = 0; y < cls.length; y++) {
              if (classes[x].selectorText == cls[y]) {
                val += ' ' + ((classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText).split('filter')[1].replace(/[:;} ]/g, '');
              }
            }
          }
          return val;
        }
        var val = getStyle(['.fil-bright-175','.fil-blur-1']);
        val = '.fil-bright-175.fil-blur-1 {filter:' + val + '}';
    
        var head = d.head || d.getElementsByTagName('head')[0],
            style = d.createElement('style');
        style.type = 'text/css';
        if (style.styleSheet) {
          style.styleSheet.cssText = val;
        } else {
          style.appendChild(d.createTextNode(val));
        }
        head.appendChild(style);
    
      }, false);
    }(document, window));
    p {
      color: blue;
      background: yellow;
    }
    .fil-bright-175 {
      filter: brightness(175%);
    }
    .fil-blur-1 {
      filter: blur(1px);
    }

    I am bright

    I am blurry

    I am bright and blurry

    0 讨论(0)
提交回复
热议问题