繁体   English   中英

Chrome忽略了网址中的哈希

[英]Chrome ignoring hashes in URL

我花了相当长的时间试图找到这个问题的答案,但是还没有成功。 基本上,当他们转到healthdollars.com/#contact时,我需要将用户滚动到网站的联系部分。 这在Safari中工作得很好,但在Chrome中我没有任何运气。 我曾尝试使用jQuery / Javascript强制浏览器向下滚动,但我一直无法这样做。

有人有什么想法吗? 这让我发疯-尤其是因为这样做很简单。

不是一个完整的答案,但是在Chrome中,如果您禁用Javascript,我相信您会获得所需的行为。 这使我相信您的JavaScript中的某些内容阻止了默认浏览器行为。

在我看来,首次加载页面时目标元素不存在。 如果导航到页面然后添加哈希,我没有任何问题。

if (window.location.hash.length && $(location.hash)) {
  window.scrollTo(0, $(location.hash).offset().top)
}

检查哈希,找到元素的页面偏移量,然后在此处滚动(x,y)。

编辑:我注意到,实际上,该页面从#contact开始,然后滚动回到顶部。 我同意其他答复者的观点,即您页面上的某些内容将您滚动到顶部。 在添加黑客之前,我会先进行搜索。

您可以使用JS进行此操作,例如,如果您有JQuery。

$(function(){
  // get the selector to scroll (#contact)
  var $to = $(window.location.hash);

  // jquery animate
  $('html'/* or body */).animate({ scrollTop: $to.offset().top });
});

名称属性在HTML 5中不存在,因此当您使用DOCTYPE html时,chrome看起来已经使名称属性过时了。

其他浏览器尚未赶上。

更改

<a name="contact"></a>

<a id="contact"></a>

也许使用香草javascript的变通办法可能会有用:

// Get the HTMLElement that you want to scroll to. 
var element = document.querySelector('#contact');
// Stories the height of element in the page.
var elementHeight = element.scrollHeight;
// Get the HTMLElement that will fire the scroll on{event}.
var trigger = document.querySelector('[href="#contact"]');    
trigger.addEventListener('click', function (event) {
  // Hide the hash from URL.
  event.preventDefault();
  // Call the scrollTo(width, height) method of window, for example.
  window.scrollTo(0, elementHeight);
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM