[英]How to extract individual CSS filter functions from an element's style?
我的 HTML 頁面上有一張圖像,上面應用了一些過濾器。 它的style
屬性可能如下所示:
filter: brightness(85%) contrast(136%) saturate(122%) drop-shadow(0 0 5px #000000) grayscale(25%)
我想做的是從這個字符串中提取單個樣式函數,並將它們存儲到 object 或數組中,例如:
{ "brightness": "80%", "contrast": "136%" /* and so on ... */ }
或者:
[["brightness", "80%"], ["contrast", "136%"] /* and so on ... */ ]
有沒有一種簡單的方法可以做到這一點?
我希望這是你所要求的。
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>
你可能會做這樣的事情。
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";
}
}
然后只存儲那些道具是過濾器的
代碼直接來自MDN
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.