\ifnumequal{\thepage} 不适用于新页面的第一段

\ifnumequal{\thepage} 不适用于新页面的第一段

如果链接的目标与参考位于同一页面上,我将使用此代码来阻止超链接:\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

相关内容