简体   繁体   中英

How to extract individual CSS filter functions from an element's style?

I have an image on my HTML page with some filters applied to it. Its style attribute might look like this:

filter: brightness(85%) contrast(136%) saturate(122%) drop-shadow(0 0 5px #000000) grayscale(25%)

What I want to do is to extract individual style functions from this string, and store them into an object or an array, like:

{ "brightness": "80%", "contrast": "136%" /* and so on ... */ }

or:

[["brightness", "80%"], ["contrast", "136%"] /* and so on ... */ ]

Is there an easy way of doing this?

  1. get the value of the filter in css as a string
  2. get the position of every filter in the styles string
  3. get the array of filters and the position in the styles string
  4. order the previous array by the index (the position)
  5. build the pairs filter, value.

I hope this is what you are asking for.

 let para = document.querySelector('p');// the filtered element let s = window.getComputedStyle(para);//get the style for the filtered element let theFilter = s.getPropertyValue("filter");//get the value of the filter // the array of all the filters in css let filters = ["blur","brightness","contrast","drop-shadow","grayscale","hue-rotate","invert","opacity","saturate","sepia","url"]; // an empty array let ry = []; filters.forEach((f,i)=>{ let oF = theFilter.match(f); if(oF){ ry.push({prop:oF[0],index:oF.index}) } }) // ry is the array of the filters and the position in theFilter string [{prop: "brightness", index: 0},{prop: "contrast", index: 17}... function compareNumbers(a, b) { return a.index - b.index; } // order the ry array by index let sortedry = ry.sort(compareNumbers); // the object with the filters let oFilters = {} for(let i = 0; i < sortedry.length; i++){ let sbstr = (i+1 < sortedry.length)? theFilter.substring(sortedry[i].index,sortedry[i+1].index).trim(): theFilter.substring(sortedry[i].index).trim() let value = sbstr.substring(sbstr.indexOf("(")+1, sbstr.length-1); oFilters[sortedry[i].prop] = value; } console.log(oFilters)
 p{filter: brightness(85%) contrast(136%) saturate(122%) drop-shadow(0 0 5px #000000) grayscale(25%)}
 <p>The filtered element</p>

You might do something like this.

    var element = document.getElementById("myElement");
    var out = "";

    var elementStyle = element.style;
    var computedStyle = window.getComputedStyle(element, null);

    for (prop in elementStyle) {
      if (elementStyle.hasOwnProperty(prop)) {
        out += "  " + prop + " = '" + elementStyle[prop] + "' > '" + computedStyle[prop] + "'\n";
      }
    }

then store only those that the prop is filter

the code come directly from MDN

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

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