我的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 ... */ ]
有一种简单的方法吗?
答案 0 :(得分:2)
我希望这就是您要的。
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>