gpt4 book ai didi

javascript - JS计算父元素中子元素的宽度

转载 作者:行者123 更新时间:2023-11-30 20:58:40 25 4
gpt4 key购买 nike

出于某种原因,这个琐碎的任务让我很头疼。

到目前为止我有

<div class="nowrap">
<span>Content</span>
<span>Content</span>
<span>Content</span>
</div>

<div class="nowrap">
<span>Content</span>
<span>Content</span>
</div>

var width = 0;
$('.nowrap').each(function() {
width += $(this).outerWidth( true );
});
console.log(width) //1946

这给了我 .nowrap parent 下所有 child 的总和。但我想要的是每个 .nowrap 有 2 个独立的值 children 的。所以如果我有 3 个 .nowrap div,我会得到类似

的东西
[443 totalWidth of .nowrap, 755 totalWidth of .nowrap, 457 totalWidth of .nowrap]

做什么?

https://codepen.io/umbriel/pen/JOOxeL

最佳答案

我知道这是用 jQuery 标记的,但出于礼貌起见,我将提供一个仅使用标准函数的解决方案:

let totalWidths = Array.from(
document.querySelectorAll('.nowrap'),
nowrap => Array.from(
nowrap.children,
child => child.offsetWidth
).reduce((total, width) => total + width)
)

console.log(totalWidths)
<div class="nowrap">
<span>div→ [2035] — </span>
<span> Funky figures </span>
<span>6'2" • 180° m² </span>
</div>

<div class="nowrap">
<span> Sick ligatures </span>
<span class="dlig">rf rt</span>
</div>

关于javascript - JS计算父元素中子元素的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47356566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com