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

LaTeX中mdframed环境条件着色问题求助

LaTeX mdframed 条件着色问题修复

问题原因

你的代码无法运行的核心问题是:mdframed的键值参数(如backgroundcolor)要求传入可直接展开为颜色值的内容,而xstring包的\IfStrEqCase是执行型命令,不会直接返回颜色字符串,而是在运行时才处理逻辑,直接将\colorMap{a}传入backgroundcolor会被解析为无效的颜色指令,导致编译失败。

修复方案

方案1:改用可展开的条件判断(推荐)

使用etoolbox包的可展开命令\ifdefstring,它能直接返回颜色值,适合在mdframed的键值参数中使用:

\documentclass{article}
\usepackage{etoolbox}
\usepackage{mdframed}

% 定义可展开的颜色映射命令
\newcommand{\colorMap}[1]{%
  \ifdefstring{#1}{a}{green}{%
    \ifdefstring{#1}{b}{yellow}{%
      \ifdefstring{#1}{c}{red}{white}% 未匹配时用白色作为默认
    }%
  }%
}

\begin{document}
\begin{mdframed}[backgroundcolor=\colorMap{a}]
\textbf{Color}
\end{mdframed}
\begin{mdframed}[backgroundcolor=\colorMap{b}]
\textbf{Color}
\end{mdframed}
\begin{mdframed}[backgroundcolor=\colorMap{c}]
\textbf{Color}
\end{mdframed}
\begin{mdframed}[backgroundcolor=\colorMap{d}]
\textbf{Color}
\end{mdframed}
\end{document}

方案2:保留xstring,先预存颜色值

如果一定要使用xstring,需要先将颜色值存入一个临时宏,再将宏传入backgroundcolor:

\documentclass{article}
\usepackage{xstring}
\usepackage{mdframed}

\newcommand{\colorMap}[1]{%
  \IfStrEqCase{#1}{%
    {a}{\def\currentColor{green}}%
    {b}{\def\currentColor{yellow}}%
    {c}{\def\currentColor{red}}%
  }[\def\currentColor{white}]% 未匹配时用白色作为默认
}

\begin{document}
% 先调用命令设置临时颜色宏
\colorMap{a}
\begin{mdframed}[backgroundcolor=\currentColor]
\textbf{Color}
\end{mdframed}

\colorMap{b}
\begin{mdframed}[backgroundcolor=\currentColor]
\textbf{Color}
\end{mdframed}
\end{document}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:13:17