首页 > 解决方案 > 如何从元素的样式中提取单个 CSS 过滤器功能?

问题描述

我的 HTML 页面上有一张图像,上面应用了一些过滤器。它的style属性可能如下所示:

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

我想要做的是从这个字符串中提取单个样式函数,并将它们存储到一个对象或数组中,例如:

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

或者:

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

有没有一种简单的方法可以做到这一点?

标签: javascripthtmlcsscss-filters

解决方案


  1. 获取css中过滤器的值作为字符串
  2. 获取样式字符串中每个过滤器的位置
  3. 获取过滤器数组和样式字符串中的位置
  4. 按索引(位置)对前一个数组进行排序
  5. 构建对过滤器,值。

我希望这是你所要求的。

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>


推荐阅读