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

如何根据链接类型取消ViewTransitions API的页面过渡动画?

解决ViewTransitions API无法终止特定页面过渡的问题

首先,你的代码存在两个核心问题:

  • 字符串分割逻辑错误:event.target.href.split('.')[0]会把works.php拆成works,但你的restrictedPages里存的是带后缀的文件名,导致匹配失败。
  • 调用skipTransition()的时机不对:startViewTransition()是主动触发过渡的方法,你不能先启动过渡再跳过,而是应该直接不启动过渡来达到禁用效果。

结合你的需求(仅index -> works禁用过渡,其他跳转保留过渡),正确的实现方式如下:

// 获取当前页面的文件名
const currentPage = window.location.pathname.split('/').pop();

function handleLinkClick(event) {
  // 仅处理站内链接
  if (!event.target.matches('a[href^="./"]') && !event.target.matches('a[href^="/"]')) return;
  
  event.preventDefault();
  const targetPage = event.target.href.split('/').pop();

  // 精准判断需要禁用过渡的跳转组合:当前是index.php,目标是works.php
  const shouldSkipTransition = currentPage === 'index.php' && targetPage === 'works.php';

  if (shouldSkipTransition) {
    // 直接跳转,不触发ViewTransition
    window.location.href = event.target.href;
  } else {
    // 启用ViewTransition的跳转
    document.startViewTransition(() => {
      window.location.href = event.target.href;
    });
  }
}

// 给所有链接绑定点击事件
document.addEventListener('click', handleLinkClick);

关键说明:

  • 精准匹配跳转组合:不再用模糊的页面列表,直接锁定index.php到works.php的跳转,完全贴合你的需求。
  • 提前拦截默认导航:通过preventDefault()阻止浏览器默认跳转行为,再根据条件选择是否用ViewTransition包裹导航动作。
  • 过滤外部链接:避免逻辑作用到站外链接上,保证只处理项目内页面跳转。

如果后续需要扩展禁用过渡的跳转组合,只需修改shouldSkipTransition的判断逻辑即可,比如:

const restrictedJumps = [
  { from: 'index.php', to: 'works.php' },
  { from: 'works.php', to: 'index.php' } // 若需反向跳转也禁用,可添加此规则
];
const shouldSkipTransition = restrictedJumps.some(item => item.from === currentPage && item.to === targetPage);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 20:34:58