【问题标题】:Get values from one .each function into a different .each function从一个 .each 函数中获取值到不同的 .each 函数中
【发布时间】:2018-04-16 14:07:22
【问题描述】:

我有 4 个带有 display: block; width: 100%; 的子横幅,每个子横幅都有一个带有文本的 div。这些 div 使用transform: translateY(238px) 挂在父元素之外。

每个包含文本的 div 的高度都不同,所以我试图编写一个函数来检查每个文本 div 的高度,并相应地将边距应用于该特定父元素的底部。

到目前为止我得到的是这个,但我不知道如何将变量respectiveMargin 传递到我的第二个每个函数中,以便它与正确的父元素匹配。现在它只是对所有子横幅应用相同的边距。感谢您的所有帮助!

const resize = () => {

  if ($(window).width() < 768) {
    $('.sub-banner-text-wrapper').each(function () {
      var textHeight = $(this).height();
      var responiveMargin = (textHeight - 62) + 25;
    });

    $('.sub-banner').each(function () {
        $(this).css("margin-bottom", responiveMargin);
    });
  }

};
$(window).on('resize', resize);

【问题讨论】:

  • 目标是什么?在两行之间阅读,您试图通过添加可变数量的边距使所有子横幅具有相同的垂直高度。对吗?

标签: javascript jquery variables each


【解决方案1】:

也许是这样的?

if ($(window).width() < 768) {
        $('.sub-banner-text-wrapper').each(function () {
          var subBanner = $(this).closest('.sub-banner').attr('class');
          var textHeight = $(this).height();
          var responiveMargin = (textHeight - 62) + 25;
          $(subBanner).css("margin-bottom", responiveMargin);
        });
    }

【讨论】:

    【解决方案2】:

    似乎主要问题是您尝试使用两个.eaches,而您只需要一个:

    const resize = () => {
    
      if ($(window).width() < 768) {
        $('.sub-banner-text-wrapper').each(function () {
          var textHeight = $(this).height();
          var responiveMargin = (textHeight - 62) + 25;
    
          $(this).closest('.sub-banner').css("margin-bottom", responiveMargin);
        });
      }
    
    };
    $(window).on('resize', resize);
    

    【讨论】:

    • 看起来有一个沉默的投反对票的强盗在逍遥法外。
    • 嫉妒我们的回答 ;)
    • 看起来我们几乎都在同一时间发布了几乎确切的答案,哈哈
    • 非常感谢!为我完美地清除了它。我几乎拥有它!
    【解决方案3】:

    所以当你遍历一组时引用索引。

    var banners = $('.sub-banner');
    $('.sub-banner-text-wrapper').each(function (ind) {
      var textHeight = $(this).height();
      var responiveMargin = (textHeight - 62) + 25;
      banners.eq(ind).css("margin-bottom", responiveMargin);
    });
    

    如果它恰好是子/父元素,那么您可以选择它。

    var banners = $('.sub-banner');
    $('.sub-banner-text-wrapper').each(function (ind) {
      var textHeight = $(this).height();
      var responiveMargin = (textHeight - 62) + 25;
      //If a child
      $(this).find(".sub-banner").css("margin-bottom", responiveMargin);
      //or a parent
      $(this).parent().css("margin-bottom", responiveMargin);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-20
      • 2015-01-25
      • 2015-11-01
      • 2012-09-10
      • 2023-03-22
      • 2016-03-13
      • 2021-04-06
      • 2011-10-19
      相关资源
      最近更新 更多