WordPress站点横竖屏切换页面跳转异常问题求助
问题排查与解决方案
问题根源
你的代码存在逻辑漏洞:
- 当从页面A横屏跳转到联系页后,浏览器历史栈变为
[页面A, 联系页],且联系页也加载了这段监听代码。 - 切回竖屏时,联系页的代码执行
history.back()回到页面A;但页面A的监听代码会再次检测到 orientation 从横屏变为竖屏的变化,再次执行history.back(),导致直接退回页面A的上一级页面(比如首页),出现「后退两次」的现象。
解决方案一:区分页面执行逻辑
通过判断当前页面是否为联系页,只在对应页面执行相应逻辑,避免重复触发后退:
let landscape = window.matchMedia("(orientation: landscape)"); // 替换为你实际的联系页路径 const contactPath = "/contacts/"; const currentPath = window.location.pathname; landscape.addEventListener("change", function(e) { if(e.matches) { // 非联系页才跳转到联系页 if(currentPath !== contactPath) { window.location.href = "https://website.com/contacts/"; } } else { // 仅联系页执行后退操作 if(currentPath === contactPath) { window.history.back(); } } })
解决方案二:用本地存储记录原页面
通过 localStorage 保存跳转前的页面URL,竖屏时直接跳转回原页面,避免历史栈干扰:
let landscape = window.matchMedia("(orientation: landscape)"); const contactUrl = "https://website.com/contacts/"; const currentUrl = window.location.href; landscape.addEventListener("change", function(e) { if(e.matches) { // 不在联系页时,保存原页面URL并跳转 if(currentUrl !== contactUrl) { localStorage.setItem("lastPageBeforeContact", currentUrl); window.location.href = contactUrl; } } else { const lastPage = localStorage.getItem("lastPageBeforeContact"); if(lastPage) { window.location.href = lastPage; // 跳转后清除存储,避免后续误触发 localStorage.removeItem("lastPageBeforeContact"); } } })
注意事项
- 方案一中需确保
contactPath与你网站联系页的实际路径完全一致(注意斜杠和大小写)。 - 方案二中,如果用户在联系页刷新后切回竖屏,仍会跳转到之前记录的页面;若不需要此行为,可在联系页加载时判断屏幕方向为竖屏的话,直接清除
localStorage中的记录。
内容的提问来源于stack exchange,提问作者kuma88
相关产品推荐
相关产品推荐

