2014-09-23 19 views
0

我有這樣的JavaScript來抵消在一個頁面anchorlinks固定報頭(僅當頁面加載有錨鏈路):jQuery的錨僅在頁面加載browserproblem偏移

(function() { 
     if (document.location.hash) { 
      setTimeout(function() { 
       window.scrollTo(window.scrollX, window.scrollY - 100); 
      }, 10); 
     } 
    })(); 

的問題是這隻適用於Chrome。在firefox中,第一個錨點鏈接工作得很好,但第二,第三等關閉(第二個200xp,第三個300px等)。它在IE11中完全沒有做任何事情。 有沒有辦法做到這一點純jQuery的更好的瀏覽器兼容性?或者爲什麼Firefox和IE關閉和鉻工作?

+0

偏移應該只發生在具有錨鏈接的頁面加載中。不正常的滾動。這一點很重要,因爲我也使用視差滾動。 – ramsys2k 2014-09-23 12:25:29

回答

0

我找到了答案在這裏:offsetting an html anchor to adjust for fixed header

/** 
* Check an href for an anchor. If exists, and in document, scroll to it. 
* If href argument omitted, assumes context (this) is HTML Element, 
* which will be the case when invoked by jQuery after an event 
*/ 
function scroll_if_anchor(href) { 
href = typeof(href) == "string" ? href : $(this).attr("href"); 

// If href missing, ignore 
if(!href) return; 

// You could easily calculate this dynamically if you prefer 
var fromTop = 50; 

// If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo) 
// Legacy jQuery and IE7 may have issues: https://stackoverflow.com/q/1593174 
if(href.charAt(0) == "#") { 
    var $target = $(href); 

    // Older browsers without pushState might flicker here, as they momentarily 
    // jump to the wrong position (IE < 10) 
    if($target.length) { 
     $('html, body').animate({ scrollTop: $target.offset().top - fromTop }); 
     if(history && "pushState" in history) { 
      history.pushState({}, document.title, window.location.pathname + href); 
      return false; 
     } 
    } 
} 
}  

// When our page loads, check to see if it contains and anchor 
scroll_if_anchor(window.location.hash); 

// Intercept all anchor clicks 
$("body").on("click", "a", scroll_if_anchor); 

通過https://stackoverflow.com/users/1773904/ian-clark

0

嘗試收聽onscroll事件,然後運行。

$(window).scroll(function(){ 
    $(window).scrollTop($(window).scrollTop() - 100); 
}); 
+0

它應該是'$(window).scroll'或'window.onscroll = function',不應該嗎? – Regent 2014-09-23 12:22:46

+0

是的,謝謝。錯字。 – Scimonster 2014-09-23 12:30:16

0

下面是一個方便的jQuery功能我用散步的任何元素,也是一個jsfiddle

$(".js-scrollto").click(function() { 
    $('html, body').animate({ 
     scrollTop: $($(this).attr('href')).offset().top 
    }, 2000); 
    return false; 
});