\subsection 接受 \colorbox 作为参数,但 \section 不接受

\subsection 接受 \colorbox 作为参数,但 \section 不接受

以下包含的 mwe在取消注释\subsection{\colorbox{green}{Subtitle}} 时不起作用%\section{\colorbox{green}{Title}}

    \documentclass[11pt]{book}
        \usepackage[usenames,dvipsnames]{xcolor}    
    \begin{document}
    %\section{\colorbox{green}{Title}}
    \subsection{\colorbox{green}{Subtitle}}
    \end{document}

该错误似乎是由于 LaTeX 读取GREEN而不是 造成的green

答案1

尝试这样做:

\documentclass[11pt]{book}
        \usepackage[usenames,dvipsnames]{xcolor}    
    \begin{document}
    \section[Title]{\colorbox{green}{Title}}
    \subsection{\colorbox{green}{Subtitle}}
    \end{document}

该问题是由于在书签、目录和页眉内添加颜色框而产生的......

编辑目录中的颜色框:

\documentclass[11pt]{book}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage[pdfpagelabels]{hyperref}
        

        
\let\oldsection\section
\makeatletter
\def\section{%
\@ifstar{\@Starred}{\@nonStarred}%
}
\def\@Starred{%
\@ifnextchar[%
{\GenericWarning{}{Warning: A starred section can not have optional parameters. I am going to ignore them!}\@StarredWith}%
{\@StarredWithout}%
}      
\def\@StarredWith[#1]#2{%
\oldsection*{#2}%
}
\def\@StarredWithout#1{
\oldsection*{#1}%
}
\def\@nonStarred{%
\@ifnextchar[%
{\@nonStarredWith}%
{\@nonStarredWithout}%
}
\def\@nonStarredWith[#1]#2{%
\let\oldaddcontentsline\addcontentsline%
\def\addcontentsline##1##2##3{\oldaddcontentsline{toc}{##2}{\protect\texorpdfstring{\numberline{\thesection}#2}{##3}}}%
\oldsection[#1]{#2}%
\let\addcontentsline\oldaddcontentsline%
}
\def\@nonStarredWithout#1{%
\oldsection{#1}%
}
\makeatother
        
        
\begin{document}
    
    \tableofcontents
    
    \newpage
    \section[Title]{\colorbox{green}{Title}}
    \newpage
    \section[Title2]{\colorbox{green}{Title2}}
    \subsection[Subtitle]{\colorbox{green}{Subtitle}}
\end{document}

相关内容