嵌套样式中的 tcolorbox 选项不起作用

嵌套样式中的 tcolorbox 选项不起作用

请查看图片和代码来了解我的问题。

\documentclass{article}
\usepackage[most]{tcolorbox}

    \begin{document}

    % define a new style named selfsetcontainer by container/.code
    \tcbset{container/.code={\tcbset{selfsetcontainer/.style={#1}}},
      container/.default={}}

    \begin{tcolorbox}[container,colback=yellow,selfsetcontainer={colback=green}]
      I want green background color, but get yellow. That is to say, the option 'colback=green' in nested style does not work. Why and how to solve it?
    \end{tcolorbox}

    \end{document}

在此处输入图片描述

答案1

我认为你搞混了一些东西。你需要将选项传递给代码,而不是样式。在代码中,你定义样式。那么代码如何知道你想要定义绿色样式?这只有在你告诉代码,即向它传递参数时才会起作用。(我认为在\pgfkeysalso这里使用它有点好处,因为这减少了你陷入循环或其他沮丧的机会。)

\documentclass{article}
\usepackage[most]{tcolorbox}

\begin{document}

    % define a new style named selfsetcontainer by container/.code
    \tcbset{container/.code={\pgfkeysalso{selfsetcontainer/.style={#1}}},
      container/.default={}}

    \begin{tcolorbox}[container={colback=green},colback=yellow,selfsetcontainer]
      I want green background color, and that's what I get. I set the style in
      the \texttt{container} code, where I have decided to switch to
      \verb|\pgfkeysalso| in order to reduce the chances of confusing
      Ti\emph{k}Z, which underlies the \texttt{tcolorbox} package.
    \end{tcolorbox}

\end{document}

在此处输入图片描述

回复您的评论:是的,可以定义一个代码来定义可能为空的样式。但是,为了设置样式,您需要调用另一个代码。这导致

\documentclass{article}
\usepackage[most]{tcolorbox}

\begin{document}

    % define a new style named selfsetcontainer by container/.code
    \tcbset{container/.code={\tcbset{selfsetcontainer/.style={#1}}},
      container/.default={},
      set style/.code n args={2}{\pgfkeysalso{#1/.style={#2}}}}

    \begin{tcolorbox}[container,colback=yellow,set
    style={selfsetcontainer}{colback=green},selfsetcontainer]
      This is a rather involved way of accomplishing the same:
      \begin{enumerate}
       \item \texttt{container} is a code that defines an empty style named 
       \texttt{selfsetcontainer}.
       \item \texttt{set style} is another code that sets the style of
       container, or more generally, of any style.
       \item Finally, \texttt{container} is now a style that makes the
       background green.
      \end{enumerate}
    \end{tcolorbox}

\end{document}

在此处输入图片描述

请注意,最后两个步骤可以合并为一个(代价是结构更加复杂)。你当然你想去那边吗?

相关内容