jquery到纯Javascript以保持图像的垂直节奏

时间:2012-02-16 15:34:20

标签: javascript jquery mobile mobile-safari vertical-rhythm

为了寻求保持图像垂直节奏的解决方案,我从 Filipe Fortes http://www.fortes.com/2008/jmetronome-using-jquery-to-keep-typographic-rhythm找到了这个优秀的剧本:

        $(function() {
          var lineHeight = parseInt($('body').css('line-height'));
          function balanceHeight(el) {
              var h = $(el).outerHeight();
              var delta = h % lineHeight;
              if (delta != 0)
              {
                /* For images and objects, we want to align the bottom w/ the baseline, so we
                 * pad the top of the element. For other elements (text elements that have a
                 * scrollbar), we pad the bottom, to keep the text within on the same baseline */
                var paddingDirection = ($(el).is('img') || $(el).is('object')) ?
                                                      'padding-top' : 'padding-bottom';

                /* Adjust padding, because margin can get collapsed and cause uneven spacing */
                  var currentPadding = parseInt($(el).css(paddingDirection));
                  $(el).css(paddingDirection, currentPadding + lineHeight - delta);
              }
          }

          /* Depending on your content, you may want to modify which elements you want to adjust,
           * by modifying the selector used below. By default, we grab all img, pre, and object
           * elements. */
          $('img').each(function() {
              /* Only works if we're manipulating block objects */
              if ($(this).css('display') == 'inline')
              {
                  $(this).css('display', 'block');
              }

              /* Images need to load before you get their height */
              if ($(this).is('img'))
              {
                  $(this).load(function(){ balanceHeight(this); });
              }
              else
              {
                  balanceHeight(this);
              }
          });
        })     

它对我有用,但由于我正在开发一个移动项目,我想知道如何将它翻译成纯粹的javascript。

1 个答案:

答案 0 :(得分:0)

要将其转换为标准JavaScript,您需要做一些事情:

  1. 更改选择器(例如var images = documents.getElementsByTagName('img')
  2. 更改jQuery对象(例如,而不是.each(),我们使用for循环。请执行以下示例:

    for (var i = 0; i < images.length; i += 1) {
      // code here
    }
    
  3. 如果您希望我详细介绍,请留言。翻译这个功能并不太难。