You need to enable JavaScript to run this app. 如何使用CSS控制SVG滤镜的属性值?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用CSS控制SVG滤镜的属性值?

问题原因

直接在SVG标签的行内属性中写入CSS变量var(--illumination-power)不被浏览器解析,specularConstant这类SVG滤镜属性属于表现属性,需要通过CSS选择器赋值才能正常调用CSS变量。

修复方案

你只需要做两处修改即可生效:

  1. 删除<feSpecularLighting>标签行内的specularConstant="var(--illumination-power)"属性
  2. 在CSS中新增选择器,给feSpecularLighting元素的specularConstant属性绑定变量

完整可运行代码

@property --illumination-power {
  syntax: '<number>';
  initial-value: 1;
  inherits: true
}

:root {
  animation: my-animation 5s infinite alternate;
}

@keyframes my-animation {
  0% {
    --illumination-power: 0;
  }
  100% {
    --illumination-power: 1.2;
  }
}

body {
  margin: 0;
  background-color: black;
}

/* 新增规则,绑定CSS变量到SVG属性 */
feSpecularLighting {
  specularConstant: var(--illumination-power);
}
<svg width="100vw" height="100vh">
  <defs>
    <filter id="spotlight">
      <feSpecularLighting specularExponent="10" lighting-color="white">
        <fePointLight x="200" y="100" z="70"/>
      </feSpecularLighting>
    </filter>
  </defs>
  <rect id="light-background" x="-500%" y="-500%" width="1000%" height="1000%" fill-opacity="0" filter="url(#spotlight)"/>
</svg>

补充说明

如果页面存在多个<feSpecularLighting>标签需要不同的变量控制,给对应标签添加自定义类名,用类选择器单独设置即可。该方案兼容Chrome 85+、Firefox 79+、Safari 15.4+及以上版本的所有现代浏览器。


内容的提问来源于stack exchange,提问作者chaim770

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 10:30:05