簡體   English   中英

獲得HTML元素50%的位置

[英]get 50% position of HTML element

簡而言之,我正在嘗試編寫滾動跟蹤。 但是,我認為我的數學不適用於計算html element( section )的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]);
}

你的數學是正確的。 您唯一可以做的就是通過使用jQuery .each函數稍微簡化代碼:

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

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

請注意,如果您有一個動態頁面,並且在客戶端修改了部分位置或大小,則必須重新計算滾動位置。

工作提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM