猿问

如何在 URL 中没有 # 的情况下转到不同网站页面中的特定 div

在我的整个网站中,我有很多锚标记将用户发送到另一个网页上的特定 div(例如 href="books.php#first")。我想从 URL 中删除 #。我曾尝试使用 .htaccess 但根据我所阅读的内容,重写 # 是不可能的。我想问一下我可以使用什么另一种方法来从我的 URL 中删除 #。我发现使用 jQuery 或 JavaScript 滚动到单个网页中的特定点可以实现类似的功能,但是,我无法找到有关如何在不同页面上执行此操作的答案。


守候你守候我
浏览 170回答 1
1回答

湖上湖

您可以像这样使用 localStorage 或 sessionStorage:在锚标记所在的第一页中<a href="page.html" onclick="localStorage.setItem('anchor' , 'mydiv')"> Link</a>&nbsp;在目标页面&nbsp; &nbsp;<script>&nbsp; &nbsp; $(function () {&nbsp; &nbsp; &nbsp; &nbsp; // on document load&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // if localStorage["anchor"] is set to a value&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; let target = localStorage.getItem("anchor");&nbsp; &nbsp; &nbsp; &nbsp; if (target) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // scroll to target&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('html, body').animate({ scrollTop: $(target).offset().top }, 'slow');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // clear localStorage&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; localStorage.removeItem("anchor");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });</script>
随时随地看视频慕课网APP
我要回答