Javascript 测量多个 Div 高度

发布于 2024-12-15 10:14:27 字数 350 浏览 3 评论 0原文

我正在尝试使用 jQuery 构建一个手风琴菜单,但遇到了跳跃的动画。跳动是因为没有设置div的高度造成的。我的问题是每个 div 都会根据内容有不同的高度;所以问题是,我如何使用 javascript 来查看带有“子菜单”类的每个 div,测量它的高度并设置它。

这是我到目前为止所得到的:

$('.submenu').each(function() {
  var divh = $(this).height();
  $(this).css('height', divh + 'px');
});

我遇到的是,它似乎只测量一个 .submenu div 并将它们全部设置为该高度。想法?提前致谢!

I'm trying to build out an accordion menu with jQuery but am running into jumpy animations. The jumpiness is caused by not setting a height for the div. My problem is that each div is going to have a different height based on the contents; so the question is, how would I use javascript to look at each div with the class 'submenu', measure it's height, and set it.

Here is what I have so far:

$('.submenu').each(function() {
  var divh = $(this).height();
  $(this).css('height', divh + 'px');
});

What I'm running into is that it only seems to measure one .submenu div and sets all of them to that height. Thoughts? Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无边思念无边月 2024-12-22 10:14:27

相信我发现了问题。我将上面的脚本放在 $(document).ready() 函数中,该函数只会加载并随后测量 DOM。将其移动到 $(window).load() 函数,让它查看内容,然后测量高度。作为澄清点,.submenu 类 div 是折叠式 div。

$(window).load(function(){
  $('.submenu').each(function() {
    var divh = $(this).height();
    $(this).css('height', divh + 'px');
  });

  $('.submenu').hide();
});

Believe I found the problem. I had the above script in a $(document).ready() function which would only have loaded, and subsequently measured, the DOM. Moved it to a $(window).load() function which let it see the content and then measure the height. As a point of clarification the .submenu class divs are the accordion divs.

$(window).load(function(){
  $('.submenu').each(function() {
    var divh = $(this).height();
    $(this).css('height', divh + 'px');
  });

  $('.submenu').hide();
});
赠佳期 2024-12-22 10:14:27

假设也像这样:

$('.submenu').each(function() {
  var divh = $(this).height();
  $('.divClass').css('height',  $('.divClass').height() + divh + 'px');
});

您需要始终将当前 div 高度添加到您的手风琴 div 中

Suppose too look like this :

$('.submenu').each(function() {
  var divh = $(this).height();
  $('.divClass').css('height',  $('.divClass').height() + divh + 'px');
});

You need to always add the current div height in your for to your accordion div

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文