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

如何优化jQuery代码,使.outerHeight计算逻辑作用于所有对应div?

如何让高度计算函数作用于页面上的每一组对应div?

问题分析

你当前的核心问题出在原代码的逻辑设计上:遍历所有.content时,currentHeight会被每一次循环覆盖,最终只保留最后一个.content的高度值,再统一应用给所有.sections,自然无法实现每组对应设置高度的效果。

要达成「相邻.sections使用对应.content高度的一半」的目标,关键是让每个.sections找到它关联的那个.content元素,再单独计算并设置高度。

符合DRY原则的优化代码

你已经找对了方向,现在我们把重复的高度计算逻辑抽离成复用函数,让代码更简洁、更易维护:

jQuery(document).ready(function() {
  // 抽离高度设置逻辑为复用函数
  function setSectionHeight($section, $content) {
    if ($content.length > 0) {
      $section.css('height', $content.outerHeight() / 2);
    }
  }

  jQuery('.bigImageSections').each(function() {
    const $currentSection = jQuery(this);
    // 检查下一个元素是否为目标content
    setSectionHeight($currentSection, $currentSection.next('.translatedContent'));
    // 检查上一个元素是否为目标content
    setSectionHeight($currentSection, $currentSection.prev('.translatedContent'));
  });
});

代码细节说明

  • 用setSectionHeight函数封装重复的判断和高度设置逻辑,避免冗余代码;
  • 用$前缀标记jQuery对象,提升代码可读性,同时避免重复调用jQuery();
  • 遍历每个.bigImageSections时,分别检查它的前后元素是否为目标.translatedContent,匹配到就执行高度设置。

更高效的适配方案(针对你的HTML结构)

如果你的页面是严格的「两个.sections夹一个.content」结构,还可以换一种遍历逻辑,直接以.content为核心,一次处理对应的两个.sections,减少遍历次数:

jQuery(document).ready(function() {
  jQuery('.translatedContent').each(function() {
    const targetHeight = jQuery(this).outerHeight() / 2;
    // 给当前content前后的sections设置高度
    jQuery(this).prev('.bigImageSections').css('height', targetHeight);
    jQuery(this).next('.bigImageSections').css('height', targetHeight);
  });
});

这个版本逻辑更贴合你的HTML结构,执行效率也更高,能直接实现你要的「前两个.sections高度100px,后两个200px」的预期效果。


内容的提问来源于stack exchange,提问作者website walrus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:48:33