如何在 css 中分离过滤器的不同属性?



我正在制作一个垄断板,其中每个块都是一个元素。我需要根据不同的条件使块变得暗淡明亮。为了改变亮度,我使用filter属性。亮度将动态更改,因此我需要更改style.filter

现在还有其他属性,如'drop-shadow'我想保持常量,我已经在 css 文件中使用了它们。但现在的问题是,这两个过滤器不能同时存在。有没有办法在 css 中将style.filterfilter属性结合起来。

document.querySelector('#test').style.filter = 'brightness(0.5)'
div{
height:100px;
width:100px;
border:2px solid;
background:orange;
filter:drop-shadow(2px 4px 6px black);

}
<div id="test"></div>

在上面的脚本中,我需要同时显示brightnessdrop-shadow但只有亮度在工作。

注意:在示例中,我刚刚讲述了两个属性,但在我的实际代码中还有更多属性。我知道这可以通过为 css 属性创建一个常量字符串来解决,然后每次将其连接到style.filter.但我不想这样。

使用 CSS 变量:

document.querySelector('#test').style.setProperty("--b", "0.2");
div#test{
height:100px;
width:100px;
border:2px solid;
background:orange;
filter:drop-shadow(2px 4px 6px black) brightness(var(--b,1)) blur(2px);

}
<div id="test"></div>

如果设置筛选器属性,则会重写其所有字符串,而不是追加到其中。因此,您需要创建一些变量来存储所有过滤器属性。它可以是一个用于 exaple 的数组。然后推送或拼接该数组中的属性,并使用结果更新筛选器。例如:

let arr = [];
arr.push('brightness(0.5)');
arr.push('drop-shadow(2px 4px 6px black)');

,然后更新筛选器属性:

document.querySelector('#test').style.filter = arr.join(' ');

另一种方法是编写将获取过滤器字符串的函数,将其转换为数组,然后执行与上述相同的操作。

要结合CSS和element.style.filter,你可以尝试这样的事情:

function addFilter( element, filterValue ){
let prop = getComputedStyle( element ).getPropertyValue('filter');
if( prop === 'none' ){
element.style.filter = filterValue;
} else {
let arr = prop.split(' ');
if( arr.includes(filterValue) ) return;
arr.push(filterValue);
element.style.filter = arr.join(' ');
}
}
function removeFilter( element, filterValue ){
let prop = getComputedStyle( element ).getPropertyValue('filter');
if( prop === 'none' ) return;
let arr = prop.split(' '),
index = arr.indexOf(filterValue)
if( index !== -1 ) arr.splice( index, 1 );
element.style.filter = arr.join(' ');
}
function setBrightness( element, val ){
let prop = getComputedStyle( element ).getPropertyValue('filter');
if( prop === 'none' ) prop = 'brightness(1)';
prop = prop.replace( /brightness(d+(.d+)?)/g, `brightness(${val})` );
element.style.filter = prop;
}

最新更新