![\ifnumequal{\thepage} 不适用于新页面的第一段](https://linux22.com/image/303767/%5Cifnumequal%7B%5Cthepage%7D%20%E4%B8%8D%E9%80%82%E7%94%A8%E4%BA%8E%E6%96%B0%E9%A1%B5%E9%9D%A2%E7%9A%84%E7%AC%AC%E4%B8%80%E6%AE%B5.png)
如果链接的目标与参考位于同一页面上,我将使用此代码来阻止超链接:\newcommand*{\myref}[1]{\ifnumequal{\thepage}{\getpagerefnumber{#1}}{\ref*{#1}}
但是,我刚刚意识到,如果超链接位于新页面的第一段,代码将不起作用,请参见下面的最小工作示例。有人知道哪里出了问题吗?任何帮助都非常感谢!
\documentclass{article}
\usepackage{hyperref}
\usepackage{etoolbox}
\usepackage{lipsum}
\makeatletter
\newcommand*{\myref}[1]{\ifnumequal{\thepage}{\getpagerefnumber{#1}}{\ref*{#1}}{\ref{#1}}}
\makeatother
\begin{document}
\section{first page}
Figures on first page \myref{fig:1} and second page \myref{fig:2}. \LaTeX consider this to be on page \thepage %%% links to figure 2 but not 1 - correct
Figures on first page \myref{fig:1} and second page \myref{fig:2}. \LaTeX consider this to be on page \thepage %%% links to figure 2 but not 1 - correct
\begin{figure}[ht]
\centering
\rule{6cm}{3cm}
\caption{Figure caption text} \label{fig:1}
\end{figure}
\lipsum[1-3]
\section{second page}
Figures on first page \myref{fig:1} and second page \myref{fig:2} %%% links to figure 2 but not 1 - incorrect!
Figures on first page \myref{fig:1} and second page \myref{fig:2} %%% links to figure 1 but not 2 - correct
\begin{figure}[ht]
\centering
\rule{6cm}{3cm}
\caption{Figure caption text} \label{fig:2}
\end{figure}
\end{document}
答案1
由于异步输出程序,TeX 在处理段落时通常不知道页码。因此需要在引用处添加标签来获取页码:
\usepackage{hyperref}
\usepackage{etoolbox}
\makeatletter
\newcounter{myref}
\renewcommand*{\themyref}{myref:\the\value{myref}}
\newcommand*{\myref}[1]{%
\leavevmode
\stepcounter{myref}%
\label{\themyref}%
\ifnumequal{\getpagerefnumber{\themyref}}{\getpagerefnumber{#1}}%
{\ref*{#1}}{\ref{#1}}%
}
\makeatother