You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何排除外部链接与带target="_blank"的链接执行页面过渡?

解决页面过渡效果的链接排除问题

要实现只对站内、非新窗口打开、无指定类名的链接应用过渡效果,你需要在执行过渡逻辑前添加条件判断,满足排除条件时直接让浏览器处理默认跳转行为即可。以下是修改后的完整代码:

// PAGE TRANSITION
window.onload = () => {
  const anchors = document.querySelectorAll('a');
  const transition_el = document.querySelector('.transition');

  setTimeout(() => {
    transition_el.classList.remove('is-active');
  }, 350);

  for (let i = 0; i < anchors.length; i++) {
    const anchor = anchors[i];

    anchor.addEventListener('click', e => {
      // 获取当前绑定事件的a标签(避免点击子元素时找不到对应锚点)
      const currentAnchor = e.currentTarget;
      // 1. 判断是否是外部链接
      const isExternal = new URL(currentAnchor.href).hostname !== window.location.hostname;
      // 2. 定义需要跳过过渡的所有条件:新窗口打开、外部链接、带自定义排除类名
      const shouldSkipTransition = 
        currentAnchor.target === '_blank' || 
        isExternal || 
        currentAnchor.classList.contains('no-transition');

      // 满足排除条件时,直接放行,不执行过渡
      if (shouldSkipTransition) {
        return;
      }

      // 仅对需要过渡的链接,阻止默认跳转并执行过渡逻辑
      e.preventDefault();
      let target = getLink(e);

      if (!target) return; // 处理href为空的异常情况

      transition_el.classList.add('is-active');

      // 用setTimeout替代setInterval(setInterval会重复执行,这里只需一次跳转)
      setTimeout(() => {
        window.location.href = target;
      }, 350);
    })
  }
}

function getLink(e) {
  if (e.target.hasAttribute("href"))
    return e.target.href;
  var parent = e.target.parentNode;
  while (parent != null && typeof parent.tagName != "undefined") {
    if (parent.hasAttribute("href"))
      return parent.href;
    parent = parent.parentNode;
  }
  return null;
}

关键修改说明

  • 排除条件判断:

    • 检查target="_blank":直接通过currentAnchor.target判断,满足则跳过过渡,保留新窗口打开的默认行为
    • 识别外部链接:利用URL对象解析链接的hostname,和当前页面的window.location.hostname对比,不一致则判定为外部链接
    • 自定义排除类名:给不需要过渡的链接添加class="no-transition",通过classList.contains识别
  • 逻辑顺序调整:先判断是否需要排除,再决定是否阻止默认跳转,避免原本忽略target="_blank"的问题

  • 替换setInterval为setTimeout:原代码中setInterval会每隔350ms重复执行跳转,这是错误的,改成setTimeout只执行一次跳转

使用说明

  • 外部链接、带target="_blank"的链接会自动跳过过渡,正常执行默认行为
  • 如果你想手动排除某些特定链接,只需给该a标签添加class="no-transition"即可

内容的提问来源于stack exchange,提问作者Marielle Nadeau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 17:15:02