Jak*_*ke_ 21 html html5 google-chrome cross-browser
这是我在我的页面上使用的代码,
<li><a href="/explore/#Sound">Sound</a></li>
Run Code Online (Sandbox Code Playgroud)
(在所有页面上显示的菜单中)
<a id="Sound"><a>
Run Code Online (Sandbox Code Playgroud)
(在我要链接的页面上)
我尝试使用id向标记添加内容.但只有在chrome中,浏览器才会向下滚动到标记.这些锚点在IE和FF中有效吗?
Jak*_*ke_ 41
事实证明这是某些版本的Chrome中的一个错误,为需要它的任何人发布了解决方法!:)
$(document).ready(function () {
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (window.location.hash && isChrome) {
setTimeout(function () {
var hash = window.location.hash;
window.location.hash = "";
window.location.hash = hash;
}, 300);
}
});
Run Code Online (Sandbox Code Playgroud)
小智 24
发布的解决方法对我来说不起作用,但经过几天的搜索后,这终于像魅力一样工作,所以我觉得值得分享:
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
如果您在发现指向 SPA 站点的锚链接在外部站点上不起作用时以某种方式像我一样结束了这里。是的,浏览器的工作速度太快而无法加载页面的骨架。它在加载页面时找不到您的锚点。
要解决这个问题,只需在 SPA 的生命周期(useEffect在 React 和mountedVue 中)添加一些行来检查 url 哈希并自己进行滚动。
使用 React 的例子
useEffect(()=> {
if(document.location.hash === '#some-anchor') {
setTimeout(()=> {
document
.querySelector("#some-anchor")
.scrollIntoView({ behavior: "smooth", block: "start" })
}, 300)
}
}, [])
Run Code Online (Sandbox Code Playgroud)