我现在有一个需求,鼠标悬浮a标签浏览器左下角显示虚拟路劲点击跳转到真实路劲
我用springboot html也写后端使用Thymeleaf作为模板引擎
设置下 target = _blank
要实现点击跳转后地址栏上显示虚拟路径,你可以使用HTML5的History API,利用pushState()方法将虚拟路径推入浏览器历史记录中,从而改变浏览器地址栏上的显示。
可以修改你的代码如下:
<a href="虚拟路径" data-href="真实路径">a标签</a>
const allA = document.querySelectorAll('a');
allA.forEach((item)=>{
item.onclick = function(e){
if(this.getAttribute("data-href")){
e.preventDefault();
const virtualPath = this.getAttribute("href");
const realPath = this.getAttribute("data-href");
window.history.pushState({path: virtualPath}, '', virtualPath);
window.location.href = realPath;
}
}
});
点击a标签时,先使用e.preventDefault()阻止默认的跳转行为,然后使用pushState()方法将虚拟路径推入历史记录中,最后再通过window.location.href跳转到真实路径。
注意,
这个代码片段可以实现在跳转后浏览器地址栏显示虚拟路径的功能,但是需要注意,如果用户直接在地址栏中输入真实路径,浏览器仍会跳转到真实路径,这时就需要在后端服务器上进行重定向操作来解决。
希望能帮助到你,如有用,请采纳,谢谢
该回答引用GPTᴼᴾᴱᴺᴬᴵ
您可以在点击跳转后修改浏览器的地址栏路径来实现您的需求。在您的代码中,当用户点击a标签时,您可以使用window.history.pushState()方法来修改浏览器地址栏路径。
具体的代码实现如下:
<a href="虛拟路劲" data-href="真实路劲" onclick="handleClick(event)">a标签</a>
<script>
function handleClick(e) {
e.preventDefault();
const dataHref = this.getAttribute("data-href");
if (dataHref) {
window.history.pushState({}, null, 虚拟路劲);
window.location.href = dataHref;
}
}
</script>
其中,window.history.pushState()方法的第一个参数可以传递任意对象,表示新状态的数据;第二个参数可以传递页面标题,但通常可以传入null;第三个参数是新的虚拟路劲。在实际使用中,您需要将虚拟路劲替换成您需要的路径。
·
请注意,在使用这种方法时,用户刷新页面会直接访问虚拟路径而非真实路径,因此您需要确保您的后端服务能够正确处理这种情况。