2015-10-16 27 views
1

,我試圖寫滾動跟蹤。但是,我不認爲我的數學計算html元素的50%偏移量是正確的(section)。在堅果殼中獲得HTML元素的50%位置

有人可以看看這個,並告訴我,如果它是錯誤的/正確的,或者如果有可能有更好的方法來計算50%的標記/偏移量。

// add the section elements into an array 
var sections = $('section'); 


// define variables and arrays 
var currentOffset = 0, 
    lastScrollTop = 0, 
    i = 0, 
    offsets = [], 
    sectionHeights = []; 

// loop through sections and get 50% of height and add it to the .offset().top 
for (i = 0; i < sections.length; i++) { 
    sectionHeights.push($(sections[i]).height()/2); 
    offsets.push($(sections[i]).offset().top + sectionHeights[i]); 
} 

回答

2

你的數學是正確的。你能做的唯一的事情就是通過使用jQuery .each功能簡化代碼一點:

var currentOffset = 0, 
    lastScrollTop = 0, 
    i = 0, 
    offsets = []; 

$('section').each(function(){ 
    offsets.push($(this).offset().top + $(this).height()/2); 
}); 

請注意,如果你有一個動態頁面和各部分的位置或大小得到修改在客戶端,你將不得不重新計算滾動位置。

Working fiddle