You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过document.querySelector获取元素的--duration自定义属性值?

提取CSS自定义变量--duration的值

要获取--duration对应的"00:13:19",你需要读取元素的CSS自定义属性值,具体步骤如下:

  1. 先获取目标元素:
const timestampElem = document.querySelector(".current-timestamp");
  1. 读取自定义属性值,有两种常用方式:
    • 方式一:获取计算后的样式(推荐,适配变量被动态修改或继承的场景)
      const duration = getComputedStyle(timestampElem).getPropertyValue("--duration").trim();
      
    • 方式二:直接读取行内样式(仅适用于变量写在元素style属性内的场景)
      const duration = timestampElem.style.getPropertyValue("--duration").trim();
      

执行后duration变量就会存储"00:13:19",调用trim()是为了去除属性值前后可能存在的空格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:30:47