简而言之,我正在尝试编写滚动跟踪。但是,我认为我的数学方法不适合计算 html 元素 (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);
});
请注意,如果您有一个动态页面并且部分位置或大小在客户端被修改,您将不得不重新计算滚动位置。
关于javascript - 获取 HTML 元素的 50% 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33172077/