可以使用HTML5中的History API来监听URL的变化,而不刷新页面。具体实现步骤如下:

  1. 使用History API中的pushState或replaceState方法修改URL。例如:
history.pushState({}, '', '/new-url');
  1. 监听popstate事件,该事件会在浏览器的历史记录发生变化时触发。例如:
window.addEventListener('popstate', function(event) {
  console.log('URL变化:', document.location.href);
});

注意:pushState和replaceState方法并不会触发popstate事件,因此需要在修改URL的同时手动触发该事件。

完整代码示例:

// 修改URL
history.pushState({}, '', '/new-url');

// 监听popstate事件
window.addEventListener('popstate', function(event) {
  console.log('URL变化:', document.location.href);
});

// 手动触发popstate事件
window.dispatchEvent(new PopStateEvent('popstate'));
``

原文地址: http://www.cveoy.top/t/topic/giEg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录