有多种实现方式。可以用 xcolor 的 \fcolorbox,也可以用 tcolorbox。
\documentclass{ctexart}
\usepackage{xcolor}
% \usepackage{hyperref}
\definecolor{dyframecol}{HTML}{8080FF}
\definecolor{dybackcol}{HTML}{E6E6FF}
\newcounter{dycnt}
%% 第一种
\counterwithin{dycnt}{section}
\renewcommand{\thedycnt}{\arabic{section}.\arabic{dycnt}}
\newcommand{\dy}{\leavevmode\refstepcounter{dycnt}\nobreak
\fcolorbox[HTML]{8080FF}{E6E6FF}{\thedycnt}~}
%% 第二种
\usepackage{tcolorbox}
\newtcbox[use counter=dycnt, number within=section,
number freestyle=\noexpand\arabic{section}:\noexpand\arabic{dycnt}]
{\Dybox}[1][]
{colframe=dyframecol, colback=dybackcol,
boxrule=0.4pt, boxsep=0pt, left=3pt,right=3pt,top=3pt,bottom=3pt,
sharp corners, on line, after=~, #1}
% \tcbset{IfBlankF/.code n args={2}{\ifblank{#1}{}{\pgfkeysalso{#2}}}} % 如果比TeXLive2023旧,加上这个
\newcommand{\Dy}[1][]{\Dybox[IfBlankF={#1}{label={#1}}]{\thedycnt}\ignorespaces}
\begin{document}
\section{节}
\dy \label{dy:1}这是一段文字
\dy 这是一段文字 \ref{dy:4}
\Dy 这是一段文字 \ref{dy:1}
\Dy[dy:4] 这是一段文字
\end{document}
用法有一点点区别。但效果都是一样的。





问 如何输出一个行间的只显示计数器的数字的盒子