You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery/JS快速获取父元素下所有子元素的offsetTop并转为数组?

获取父元素子元素offsetTop值的简洁写法

jQuery 实现方案

直接利用jQuery的.map()方法就能快速生成目标数组,无需手动循环:

// 方式1:jQuery对象链式调用
var tops = $("#storage").children().map(function() {
  return $(this).offset().top;
}).get();

// 方式2:全局$.map方法
var tops = $.map($("#storage").children(), function(element) {
  return $(element).offset().top;
});

说明:.map()会遍历所有子元素,返回每个元素的offsetTop值;.get()用于将jQuery包装的结果转换为原生JavaScript数组,最终得到[122,213,123]这类格式。

原生JavaScript实现(可选)

如果不需要依赖jQuery,原生JS也能简洁实现:

var tops = Array.from(document.querySelector("#storage").children).map(el => el.offsetTop);

内容的提问来源于stack exchange,提问作者Error 2.0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 04:13:08