簡體   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