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

为何无法通过JS获取div的CSS自定义属性--rows和--columns的值?

问题:获取CSS自定义属性值为空的原因及解决办法

我有一个由另一JS脚本设置样式的div,想要在另一个JS文件中获取其CSS自定义属性--rows和--columns的值,但使用rowscolumns.style.getPropertyValue方法获取后,控制台输出为空。相关代码如下:

获取值的JS代码

const rowscolumns = document.getElementById('sliderh')
var rows = rowscolumns.style.getPropertyValue("--rows")
var columns = rowscolumns.style.getPropertyValue("--columns")
console.log(rows)

HTML结构

<div id="sliderh" class="slider_box" style="--relative_pos:46.5px; --rows:7; --columns:5;">
  ...
</div>

设置样式的JS函数

function relcalch() {
let relPos2 = (valueh * Stepsh) / hWidth * 100
elementh.style.setProperty("--relative_pos",`${relPos2}%`)
elementh.style.setProperty("--rows",`${valueh + 3}`)
elementh.style.setProperty("--columns",`${valuew + 3}`)
texth.innerHTML = valueh +3
}

问题原因

  • 元素的.style属性仅能读取内联样式中直接定义,或是通过.style.setProperty方法设置的属性。如果你的获取代码在relcalch函数执行前就运行,此时属性还没被设置,自然返回空。
  • 另一个可能:elementh是否指向#sliderh这个DOM元素?如果两者不是同一个元素,那属性根本没设置到目标div上,肯定拿不到值。

解决办法

  1. 保证获取代码在属性设置后执行
    把获取逻辑放在relcalch执行之后,或者绑定到触发属性变更的事件(比如滑块的input事件)中:

    // 示例:调用relcalch后立即获取
    relcalch();
    const rowscolumns = document.getElementById('sliderh');
    const rows = rowscolumns.style.getPropertyValue("--rows");
    const columns = rowscolumns.style.getPropertyValue("--columns");
    console.log(rows);
    
  2. 改用getComputedStyle获取最终生效样式
    getComputedStyle能拿到元素最终应用的所有CSS属性值,不管属性来自内联、样式表还是JS设置,兼容性和可靠性更强:

    const rowscolumns = document.getElementById('sliderh');
    const computedStyle = window.getComputedStyle(rowscolumns);
    const rows = computedStyle.getPropertyValue("--rows");
    const columns = computedStyle.getPropertyValue("--columns");
    console.log(rows); // 输出正确的属性值
    
  3. 验证elementh的指向
    确认elementh的赋值是document.getElementById('sliderh'),如果不是,修正elementh的定义,确保属性被设置到目标div上。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:05:41