如何从元素样式中提取单个CSS过滤器函数?

时间:2019-11-18 15:48:44

标签: javascript html css css-filters

我的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 ... */ ]

有一种简单的方法吗?

1 个答案:

答案 0 :(得分:2)

  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>