這是來自jquery文檔: 「.offset()方法允許我們檢索元素相對於文檔的當前位置。」 我不明白爲什麼FF或Chrome返回$('html')。offset()。頂部相對於客戶端屏幕/看來IE的方法更具可預測性。
試一下(使用DOM元素的.scrollTop屬性,而不是.offset()頂部。):
$(document).ready(function(e){
//alert("subPos: " + subPos);
//first find the position of the things to sticky
submenu = $("#sub");
//submenu.removeClass("no-js");
subPos = $("#sub").position();
subPos = subPos.top;
var preScrollHtml = document.getElementsByTagName('html').item(0).scrollTop;
var preScrollBody = document.getElementsByTagName('body').item(0).scrollTop;
var checkPos = function(){
var scrolledHtml = document.getElementsByTagName('html').item(0).scrollTop;
var scrolledBody = document.getElementsByTagName('body').item(0).scrollTop;
if (preScrollHtml !== scrolledHtml) {
windowPos = scrolledHtml;
}
else {
windowPos = scrolledBody;
}
preScrollHtml = scrolledHtml;
preScrollBody = scrolledBody;
calculate();
}
var calculate = function() {
subPos = 64;
if (windowPos >= subPos){
$("#sub").addClass("fixed");
$("#minestre").css("marginTop", "50px");
}
else if (windowPos < subPos){
$("#sub").removeClass("fixed");
$("#minestre").css("marginTop", "0px");
}
//Setting text fields to show the values of everything can help in debugging
$("#windowpos").val(windowPos);
$("#subp").val(subPos);
}
//every time the window scrolls, this function is run
if ($(window).scroll){
$(window).scroll(checkPos);
}
else if(window.onscroll){
window.onscroll = checkPos;
}
});
因此,** ** **適用於IE和FF,但不適用於Chrome。我使用了一個if/else來使用chrome來使用之前做過的工作,但它計算窗口位置的方式不同,所以這是一個全新的蠕蟲罐。 謝謝雖然,這有助於:) – andyjv
我現在看到的唯一解決方法是檢查滾動事件處理程序。「body」或「html」的.scrollTop屬性是否已更改並分配給windowPos相應的值。我將編輯我的答案來演示 – user907860