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

Next.js 13.3.0中如何为Tidio脚本添加自定义样式?

解决Next.js 13.3.0 + MUI环境下Tidio聊天框位置调整问题

下面提供几种可行的解决方案,针对你之前尝试无效的问题逐一修正:

方案1:通过next/script动态注入样式表

Tidio的iframe是脚本加载后动态生成的,静态CSS可能在iframe创建前就完成解析,导致样式无法绑定。我们可以在Tidio脚本加载完成后,动态插入样式标签:

import Script from 'next/script';

export default function Layout({ children }) {
  return (
    <>
      {children}
      <Script
        src="//code.tidio.co/123.js"
        onLoad={() => {
          // 创建并插入样式标签
          const styleTag = document.createElement('style');
          styleTag.textContent = `
            #tidio-chat-iframe {
              bottom: 150px !important;
              width: 300px !important;
            }
            @media only screen and (max-width: 980px) {
              #tidio-chat-iframe {
                bottom: 150px !important;
              }
            }
          `;
          document.head.appendChild(styleTag);
        }}
      />
    </>
  );
}

方案2:全局CSS提升选择器优先级

如果使用全局CSS文件,需要通过更具体的选择器覆盖Tidio默认样式:

  1. 在Next.js 13的App Router中,将样式写入app/globals.css;Pages Router则在_app.js中导入全局CSS文件
  2. 编写如下样式:
/* 增加选择器特异性,确保优先级高于Tidio默认样式 */
body #tidio-chat-iframe {
  bottom: 150px !important;
  width: 300px !important;
}

@media only screen and (max-width: 980px) {
  body #tidio-chat-iframe {
    bottom: 150px !important;
  }
}

方案3:利用MUI的GlobalStyles组件注入样式

适配MUI项目的风格,用GlobalStyles直接在组件中注入全局样式:

import { GlobalStyles } from '@mui/material';
import Script from 'next/script';

export default function Layout({ children }) {
  return (
    <>
      <GlobalStyles styles={{
        '#tidio-chat-iframe': {
          bottom: '150px !important',
          width: '300px !important',
        },
        '@media only screen and (max-width: 980px)': {
          '#tidio-chat-iframe': {
            bottom: '150px !important',
          }
        }
      }} />
      <Script src="//code.tidio.co/123.js" />
      {children}
    </>
  );
}

之前方法无效的原因

  • 导入CSS未生效:Tidio iframe加载晚于CSS解析,且选择器优先级不足,被默认样式覆盖
  • 内联样式无效:内联样式不支持媒体查询,且脚本执行时iframe可能尚未创建,导致getElementById返回null,同时内联样式优先级可能低于Tidio内部样式规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 21:05:56