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

Next.js中如何获取DOM元素上已生效的CSS样式?

问题原因

这个问题既不是Next.js SSR特性导致的,也和useEffect依赖数组配置无关,核心问题出在样式API的使用逻辑上:

  • HTMLElement.style 属性仅能读取/修改元素的行内样式(也就是直接写在标签style属性里的样式),你通过className绑定的外部CSS类样式,不会被挂载到这个属性上,所以读取结果为空
  • 额外补充:浏览器返回的CSSStyleDeclaration属于特殊的内置对象,不是普通JSON结构,直接用JSON.stringify序列化默认也会返回空对象,需要手动提取所需属性值后再序列化
  • divEl.current作为useEffect依赖已经可以保证DOM挂载后触发逻辑,不需要额外添加其他依赖;同时useEffect本身仅在客户端执行,和SSR渲染逻辑没有关联
修复方案

替换样式获取API为window.getComputedStyle,该API可以拿到浏览器最终计算后应用在元素上的所有生效样式,覆盖行内样式、类样式、继承样式等所有来源。如果需要JSON序列化展示,手动提取需要的样式属性即可:

import { useState, useEffect, useRef } from "react";

const IndexPage = () => {
  const divEl = useRef<HTMLDivElement | null>(null);
  const [divStyle, setDivStyle] = useState<Record<string, string>>({});

  useEffect(() => {
    if (divEl.current) {
      // 获取元素最终生效的所有计算样式
      const computedStyle = window.getComputedStyle(divEl.current);
      // 按需提取需要的样式属性
      const targetStyles = {
        backgroundColor: computedStyle.backgroundColor,
        width: computedStyle.width,
        height: computedStyle.height
      }
      setDivStyle(targetStyles);
    }
  }, [divEl.current]);

  return (
    <div>
      <div ref={divEl} className="test"></div>
      <pre>{JSON.stringify(divStyle, undefined, 2)}</pre>
    </div>
  );
};
export default IndexPage;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:27:04