0

我不确定我能说得有多好,但让我试一试。

我有一个严重基于 jQuery 的网站;这意味着它的大部分内容都是由 jQuery 创建、测量和设置的。

所有这些测量值都是 px。我需要将它们转换为 em,或者最好创建一个函数来为我转换它们。如果所有字体大小都是 16 像素(或 100%),这将很容易;然而,情况并非如此。我需要它来检测容器的字体大小并从那里开始。

如果措辞不当,我深表歉意。如果你能理解这一点并帮助我,那就太好了。如果你觉得不可能,请不要回复,一切皆有可能,只看你愿意付出多少努力。

4

2 回答 2

1

我想到了。您可以在此处查看代码。

          function px_to_em(px_value, container) {
          ////////////////////////////////
          // Detect Contianer Font Size //
          ////////////////////////////////

          //Prepend a span tag to the container for testing
          $(container).prepend("<span id='wraping_span_to_test'></span>");

          //Set the span to height 1em and then save the pixel height to the container_ft_sz variable
          container_ft_size = $("#wraping_span_to_test").css({
              "font-family": "inherit",
                  "font-size": "inherit",
                  "font-style": "inherit",
                  "font-variant": "inherit",
                  "font-weight": "inherit",
                  "line-height": "inherit",
                  "margin": "0 !important",
                  "padding": "0 !important",
                  "border": "0 !important",
                  "outline": "0 !important",
                  "background-color": "aqua",
                  "height": "1em",
                  "width": " 1em",
                  "display": "block"
          }).height();

          //Remove the testing span
          $("#wraping_span_to_test").remove();

          //Use values to convert to ems
          var round_to = 1000;
          return Math.round((px_value / container_ft_size) * round_to) / round_to;
      }

这应该允许您使用 jQuery 找到按像素测量的测量值,并通过调用一个简单的函数将它们转换为 em 测量值。

于 2014-02-19T21:16:06.617 回答
0

这并不容易。考虑一下,您可以暂时插入 width:1em 的内容,以 px 为单位测量宽度,然后从那里计算所需的 em。

于 2014-02-18T23:16:12.890 回答