多行文字自动调整大小以填充父容器

时间:2019-11-22 16:52:33

标签: javascript jquery

这个想法是用文本实现容器,所以带有文本的子元素不会溢出父元素。文字具有开始大小(可以是5像素)。它必须增加其字体大小,直到宽度或高度大于父级的宽度和高度。在其他选项中,它将安装大小减去1px。

<div class="parent">
    <div class="child">
        <div class="child-title">Short</div>
    </div>
    <div class="child">
        <div class="child-title">Title Example long variant</div>
    </div>
    <div class="child">
        <div class="child-title">Text Example</div>
    </div>
    <div class="child">
        <div class="child-title">Child text Example very long title text example</div>
    </div>
</div>
<style>
.parent {
    display:flex;
    justify-content:center;
}
.child {
    disaply: inline-flex;
    justify-content: center;
    align-content: center;
    align-items: center;
    width: 200px;
    height: 120px;
    border: 1px solid black;
}
.child-title {
    font-size: 5px;
}
</style>

我在JS中真的很糟糕。我一直在寻找答案,但是没有找到可以帮助我的解决方案。我听说过jquery-textfill,但是由于某些条件,它对我来说不是一个好的解决方案(它仅适用于block,但不适用于ex。flex。我需要该脚本与flex-container一起使用。)所以我寻求帮助。 我所能做的:

var box = document.getElementsByClassName('child');

var width = box.offsetWidth;
var height = box.offsetHeight;

var text = document.getElementsByClassName('child-title');

var width = text.offsetWidth;
var height = text.offsetHeight;

if (text.offsetWidth > box.offsetWidth) {
function increaseFontSizeBy1px() {
    txt = document.getElementsByClassName('child-title');
    style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
    currentSize = parseFloat(style);
    txt.style.fontSize = (currentSize + 1) + 'px';
}
else{
};
if (text.offsetHeight > box.offsetHeight) {
function increaseFontSizeBy1px() {
    txt = document.getElementsByClassName('child-title');
    style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
    currentSize = parseFloat(style);
    txt.style.fontSize = (currentSize + 1) + 'px';
}
else{
};

因此,对于第一个脚本,必须获取容器的大小(“子标题”(文本)和“子”(文本的父母))。然后,它在每一步中将字体大小增加1px,直到“ child-title”(文本)的宽度或高度高于“ child”(父母)的宽度或高度。如果是-脚本将设置当前字体大小选项-1px。总之,它必须是带有文本的自适应多行自动填充容器。

0 个答案:

没有答案