![不带 ''tocloft'' 包的 ToC 章节的彩色背景](https://linux22.com/image/296165/%E4%B8%8D%E5%B8%A6%20''tocloft''%20%E5%8C%85%E7%9A%84%20ToC%20%E7%AB%A0%E8%8A%82%E7%9A%84%E5%BD%A9%E8%89%B2%E8%83%8C%E6%99%AF.png)
我想创建一个目录,其中的章节以彩色背景显示,就像所附图片一样,我希望在没有tocloft
(没有包或有titletoc
)的情况下做到这一点
初学者的尝试
\documentclass{book}
\usepackage{fancyhdr}
\usepackage{titletoc}
\usepackage[svgnames]{xcolor}
\renewcommand\thesection{\arabic{section}.}
\renewcommand\thesubsection{\arabic{subsection}.\arabic{section}}
\pagestyle{fancy}
\renewcommand{\headrulewidth}{0pt}
\fancyhead[LE]{}
\fancyhead[RO]{}
\fancyhead[RE]{}
\fancyhead[LO]{}
\cfoot{\thepage}
\titlecontents*{chapter}
[0pt]
{\addvspace{1mm}}
{\colorbox{MidnightBlue}{\textcolor{white}%
{\chaptername\ \thecontentslabel}}}
{}
{\colorbox{MidnightBlue}{\textcolor{white}%
{\hspace{7.5cm}\contentspage}}}
\makeatletter
\let\stdl@chapter\l@chapter
\renewcommand*{\l@chapter}[2]{%
\stdl@chapter{\colorbox{MidnightBlue}{\textcolor{white}{#1}}}{\textcolor{MidnightBlue}{#2}}}
\makeatother
\begin{document}
\tableofcontents
\chapter{Chapter One}
\section{Section Two}
\subsection{Subsection Two}
\end{document}
答案1
除了深度破解之外,最简单的方法是将命令紧紧地包裹起来tcolorbox
,\l@chapter
然后使用标准值重新定义并内部调用该命令。但是,这会在章节目录条目的上方和下方引入一些垂直间距。
目前颜色是硬编码的。
\documentclass{book}%
\usepackage{blindtext}%
\usepackage[svgnames]{xcolor}%
\usepackage{fancyhdr}%
\usepackage{tcolorbox}
\makeatletter
\let\standardlistchapter\l@chapter%
\renewcommand*{\l@chapter}[2]{%
\begin{tcolorbox}[colback={MidnightBlue},
coltext={white},
boxrule=0pt,
boxsep=0pt,%
left=0pt,top=-10pt,
right=0pt,
bottom=0pt,
arc=0pt,
auto outer arc]
\standardlistchapter{\textcolor{white}{#1}}{\textcolor{white}{#2}}%
\end{tcolorbox}%
}%
\renewcommand\thesection{\arabic{section}.}
\renewcommand\thesubsection{\arabic{subsection}.\arabic{section}}
\pagestyle{fancy}
\renewcommand{\headrulewidth}{0pt}
\fancyhead[LE]{}
\fancyhead[RO]{}
\fancyhead[RE]{}
\fancyhead[LO]{}
\cfoot{\thepage}
\makeatother
\begin{document}
\tableofcontents%
\chapter{Chapter one}
\section{First}
\blindtext[5]
\chapter{Chapter two}
\section{First}
\blindtext[5]
\end{document}