jQuery - 缩放字体大小以填充父div高度

时间:2015-05-12 03:26:35

标签: javascript jquery html css

我在父div中有两个50%宽度的div。我希望缩放font-size以在调整窗口大小时始终填充父div的高度。

<div class="wrapper">
<div class="text">
    <div class="left-text text-fill">
    <span>Paragraph of text</span>
    </div>
    <div class="right-text text-fill">
    <span>Paragraph of text</span>
    </div>
</div>
</div>

我找到的jQuery解决方案

function textfill(options)
{
    var fontSize = options.maxFontPixels;
    var t = $("span:first", this);
    var maxHeight= $(this).height();
    console.log(maxHeight);
    var textHeight;
    do {
        t.css({'font-size': fontSize});
        textHeight = t.height();
        fontSize = fontSize - 1;
    } while (textHeight > maxHeight);
    return this;
}
$(".textfill").each(textfill({maxFontPixels: 500}));

我遇到的问题是this指的是外包装div,所以它找不到跨度。为什么没有this引用函数调用的上下文<div class="text-fill">?我将如何修复它以便它指的是div及其子跨度?

如果您需要更多代码或澄清,请与我们联系。

2 个答案:

答案 0 :(得分:0)

我解决了!我最后只需要传递this作为参数,以便函数理解上下文的含义。

$(".text-fill").each(function() {textfill(this, {maxFontPixels: 100})});
function textfill(that, options)
{
    var fontSize = options.maxFontPixels;
    var t = $("span:first", that);
    var maxHeight= $(that).height();
    var textHeight;
    do {
        t.css({'font-size': fontSize});
        textHeight = t.height();
        fontSize = fontSize - 1;
    } while (textHeight > maxHeight);
}

答案 1 :(得分:0)

这是我的解决方案:

$(".text-fill").each(function(){
    var $this = $(this), 
        fontSize = 500,
        $span = $this.children("span"),
        maxHeight= $this.height(),
        textHeight;
    console.log(maxHeight);
    $span.css({'font-size': fontSize});
    do {
        $span.css({'font-size': fontSize});
        textHeight = $span.height();        
        fontSize = fontSize - 1;
    } while (textHeight > maxHeight);    
});
div.text > div {
    width: 50%;
    float: left;
    height: 200px;
}
div.text > div > span {
    display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
<div class="text">
    <div class="left-text text-fill">
        <span>Paragraph of text</span>
    </div>
    <div class="right-text text-fill">
        <span>Paragraph of text</span>
    </div>
</div>
</div>

希望这有帮助!

相关问题