移动端JS页面重定向丢失锚点链接问题求助
嘿,这个锚点丢失的问题很常见,核心就是你原来的重定向代码没把原页面的锚点部分传递过去。别担心,只需要几行修改就能搞定!
问题根源
你原来的代码只是直接跳转到mobindex.html,完全忽略了URL里的#anchor-link部分(也就是window.location.hash属性),所以跳转后自然就丢失了锚点。
解决方案:提取并拼接锚点
我们只需要获取当前页面的锚点,然后把它拼到重定向的URL后面就行。这里有两种完善的写法:
基础版(直接传递锚点)
<script> // 检测移动设备或屏幕宽度小于600px if(/Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth < 600) { // 获取当前页面的锚点(包含#符号,比如#anchor-link) const currentAnchor = window.location.hash; // 拼接锚点到目标URL,完成带锚点的重定向 window.location.href = 'mobindex.html' + currentAnchor; } </script>
进阶版(避免循环跳转)
如果你的移动端页面mobindex.html也有类似的重定向代码,可能会出现循环跳转的问题。可以加个判断,确保只有在非移动端页面时才执行重定向:
<script> // 先判断当前页面不是mobindex.html,防止循环跳转 if (window.location.pathname !== '/mobindex.html') { // 检测移动设备或屏幕宽度 if(/Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth < 600) { const currentAnchor = window.location.hash; window.location.href = 'mobindex.html' + currentAnchor; } } </script>
关键知识点
window.location.hash:这个属性会返回当前URL中从#开始的部分,比如访问index.html#anchor-link时,它的值就是#anchor-link,直接拼接就能完美传递锚点。- 就算原URL没有锚点,
window.location.hash会是空字符串,拼接后也不会影响目标URL的正常访问。
这样修改后,当用户访问index.html#anchor-link时,就会正确重定向到mobindex.html#anchor-link啦!
内容的提问来源于stack exchange,提问作者Invincible Inv
相关产品推荐
相关产品推荐

