javascript - 获取 HTML 元素的 50% 位置

标签 javascript jquery html scroll

简而言之,我正在尝试编写滚动跟踪。但是,我认为我的数学方法不适合计算 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);
});

请注意,如果您有一个动态页面并且部分位置或大小在客户端被修改,您将不得不重新计算滚动位置。

Working fiddle

关于javascript - 获取 HTML 元素的 50% 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33172077/

相关文章:

javascript - WebRTC:使用 getStats()

jquery - 无法使用 'javascript',因为在此页的前面已经指定了另一种语言(或者从 CodeFile 属性隐含)

jquery - DataTables Ajax 加载回调

html - 嵌套 ng-repeat 无法正常工作

javascript - window.location.href 到子文件夹

javascript - 用javascript中的mysql数据库中的数据填充下拉列表

javascript - Wordpress:使用另一个自定义页面的参数调用自定义页面

html - Excel VBA HTML 嵌套查询选择器

javascript - 在同一个按钮上滑入和滑出内容

javascript - 如何在不刷新整个页面的情况下更新 HTML 文档中的 php 变量?