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

如何在href链接打开后停用加载旋转器?解决返回页面仍旋转问题

解决思路

往返缓存(bfcache)会完整保留页面跳转前的DOM状态,所以你返回原页面时,加载器的active类还在,导致旋转器一直转。最合理的处理方式是利用pageshow事件——当页面从bfcache恢复显示时,主动重置所有加载器的状态。另外还可以优化原有的点击逻辑,避免状态混乱。

具体实现

1. 监听pageshow重置加载器

当页面从bfcache中被恢复时,pageshow事件会触发,此时我们可以遍历所有处于激活状态的加载器,移除它们的active类:

2. 优化点击事件逻辑

原代码用toggle可能会导致重复点击时状态错乱,因为点击跳转只需要激活加载器,不需要切换状态,所以改为直接添加active类更稳妥。

修改后的完整代码

const buttons = document.querySelectorAll('.button-solid');

// 绑定点击事件,激活加载器
[...buttons].forEach(button => {
  button.addEventListener('click', (e) => {
    activateLoadingSpinner(e);
  });
});

// 激活加载器的函数
function activateLoadingSpinner(e) {
  // 用currentTarget确保获取到按钮本身,而不是点击的子元素
  const loader = e.currentTarget.querySelector('.lds-ring');
  if (loader) {
    loader.classList.add('active');
    [...loader.querySelectorAll('div')].forEach(child => child.classList.add('active'));
  }
}

// 监听pageshow事件,处理bfcache恢复的情况
window.addEventListener('pageshow', (e) => {
  // e.persisted为true说明页面是从bfcache取出来的
  if (e.persisted) {
    const activeLoaders = document.querySelectorAll('.lds-ring.active');
    activeLoaders.forEach(loader => {
      loader.classList.remove('active');
      [...loader.querySelectorAll('div.active')].forEach(child => child.classList.remove('active'));
    });
  }
});

注意事项

  • 不要用beforeunload事件,大多数浏览器会因为绑定了这个事件而拒绝将页面存入bfcache,反而影响页面加载性能。
  • 把e.target换成e.currentTarget是为了避免点击按钮内的加载器元素时,无法正确找到父级的加载器DOM。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:40:26