在调整大小时重新计算高度

时间:2015-12-18 02:27:52

标签: javascript jquery css window-resize equal-heights

请看CLDITY的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. How to create a jQuery function (a new jQuery method or plugin)?
  2. Run Jquery function on window events: load, resize, and scroll?
  3. How to call a function in jQuery on window resize?

1 个答案:

答案 0 :(得分:1)

我在这里为你工作: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();

});
相关问题