【问题标题】:How to accurately resize nested elements with ems and font-size percentage?如何使用 em 和字体大小百分比准确调整嵌套元素的大小?
【发布时间】:2012-11-07 22:21:00
【问题描述】:

我有一个带有每个图像的文本框的轮播,我的客户(对 HTML 一无所知)使用所见即所得的文本编辑器编辑文本框。由此产生的输出类似于你最糟糕的噩梦;类似:

<div class="carousel-text-container">
<span style="font-size:18pt;">
    <span style="font-weight:bold;">
         Lorem 
         <span style="font-size:15pt;">Dolor</span>
     </span>
    Ipsum
    <span style="font-size:19pt;">
         <span>&nbsp;</span>
         <span>Sit<span>Amet</span></span>
    </span>
</span>
</div>

这个网站必须以 3 种不同的尺寸显示以适应较小的显示器,所以我一直在使用 CSS 媒体查询来调整网站的大小。

现在我无法正确调整文本框中的文本大小。我曾尝试使用jQuery.fn.css 获取px 中每个元素的字体大小,然后将其转换为em。然后,通过在.carousel-text-container 上设置font-size:x% 类型的声明,我希望这会正确调整所有内容。

不幸的是,字体大小在 ems 中的应用似乎具有递归性质。也就是说,.example 在下面没有正确调整大小,因为它的父级也在影响它

<span style="font-size:2em;">
    Something
    <span class="example" style="font-size:1.5em;">Else</span>
</span>

如何可靠且精确地调整所有内容的大小,以便为.carousel-text-container 的所有子代实现原始字体大小、边距、填充、行高等的真实百分比?

现在,我正在构思某种递归 JavaScript 函数:

var carouselTextBoxEl;
function resizeCarouselTextBox () {
    // some example numbers thrown in
    var newWidthRatio = .8,
    function resizeCarouselTextBoxEl (el, nestedLevelNum) {
        nestedLevelNum = nestedLevelNum || 1;
            
        var childElFontSizePxStr = parseFloat(el.css('font-size')), // 16.2984392, for example
            // calculate new font size based on
            // width ratio of original size site to new size,
            // and do something with nestedLevelNum... what's the math with that?
            newChildElFontSizePxStr = childElFontSizePxStr * newWidthRatio,
            // get children of el, if any
            elChildrenEls = el.children(),
            i = elChildrenEls.length;
            
            el.css('font-size', newChildElFontSizePxStr + 'em');               
            while (--i >= 0) {
                resizeCarouselTextBoxEl(elChildrenEls[i], nestedLevelNum + 1);    
            }

    }
    
    carouselTextBoxEl.children().each(function () {
        resizeCarouselTextBoxEl($(this)
    });    
}
onSmallerScreen(resizeCarouselTextBox);

更新:我让客户利用调整某些单词的大小以用作标题等,因此我不能简单地将所有内容设置为单一字体大小。

只是一个想法:是否可以放置在 HTML5 画布中并以这种方式拍摄快照和/或调整大小?

【问题讨论】:

    标签: javascript css percentage font-size em


    【解决方案1】:

    这是 CSS(层叠样式表)的本质,所有子元素都继承其父元素的样式:)

    我会使用 jQuery 动态选择给定容器的所有子元素并更改它们的字体大小:

    $('.carousel-text-container').find('*').css('font-size', '14px');
    

    或者,您可以删除字体大小,以便所有子元素将使用为 .carousel-text-container 类声明的字体大小:

    $('.carousel-text-container').find('*').css('font-size', '');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 2011-04-25
      • 2021-09-30
      • 1970-01-01
      相关资源
      最近更新 更多