javascript - 如何从元素的样式中提取单个 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 ... */ ]
有没有一种简单的方法可以做到这一点?
解决方案
- 获取css中过滤器的值作为字符串
- 获取样式字符串中每个过滤器的位置
- 获取过滤器数组和样式字符串中的位置
- 按索引(位置)对前一个数组进行排序
- 构建对过滤器,值。
我希望这是你所要求的。
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>
推荐阅读
- php - Laravel array_forget() 助手,用于嵌套数组
- google-app-engine - Google App Engine - PHP - 邮件不工作
- java - 映射@manyToOne 不返回外键 JSON
- postgresql - 存储可以有条件地显示为文本文件一部分的文本块的最佳数据结构是什么?
- swift - 每小时安排后台任务swift 4
- matlab - 加载包含结构的巨大单元阵列
- matlab - 如何将 MATLAB 变量写入格式为 3.4d3 的文本文件
- sql-server - SSMS 批量插入 = 错误 + 是哪一行?
- composer-php - Composer 在一台计算机上非常慢,在其他计算机上没有问题
- python - Numpy 根据 XYZ 获取最大值