调整大小时重新计算高度

Making Height Recalculate on Resize

本文关键字:计算 高度 新计算 小时 调整      更新时间:2023-09-26

请参阅CODEPEN以获得澄清:http://codepen.io/geochanto/pen/LGNWML

var maxHeight = 0;
$('li a').each(function() {
    maxHeight = maxHeight > $(this).outerHeight() ? maxHeight : $(this).outerHeight();
    var linkHeight = $(this).outerHeight();
    var halfLinkHeight = parseInt(linkHeight / -2);
    $(this).  css({
   'margin-top' : halfLinkHeight,
   'height' : maxHeight
    });  
});
$("li").css("height", maxHeight);

所以我有一个代码,它计算链接的高度,然后使它们都是最高的一个的高度,并在顶部添加一些负边距,以便在它们各自的父对象内垂直居中对齐。一切都如我所愿,只是,我一直在尝试用各种方法使这个高度重新计算并应用于窗口大小调整上的<li><a>,但都没有成功。

我试过这些,但也许我的语法错了,idk:

  1. 如何创建一个jQuery函数(一个新的jQuery方法或插件)
  2. 对窗口事件运行Jquery函数:加载、调整大小和滚动
  3. 如何在窗口调整时调用jQuery中的函数

我在这里为您工作:http://codepen.io/anon/pen/RraVZE

它对css和javascript进行了一些更改。

我从你的标签上删除了绝对定位:

a {
  display: block;
  padding: 10px;
  margin-left: 50px;
  font-size: 16px;
  line-height: 1.2;
  font-family: "montserrat", Arial, Helvetica, sans-serif;
  text-transform: uppercase;
  color: #193170;
  text-decoration: none;
  word-wrap: break-word;
}

并修改了您的JavaScript:

$(document).ready(function() {
  var maxHeight = 0;
  function calculateHeight() {
    $('li a').each(function() {
      maxHeight = maxHeight > $(this).outerHeight() ? maxHeight : $(this).outerHeight();
    });
    $("li").css("height", maxHeight);
    centerText();
  }
  function centerText() {
    $('li a').each(function() {
      var linkHeight = $(this).outerHeight();
      var halfLinkHeight = parseInt((maxHeight - linkHeight) / 2);
      $(this).css('margin-top', halfLinkHeight);
    });
  }
  $(window).resize(function() {
    calculateHeight();
  });
  calculateHeight();
});