以编程方式确定单行显示的字体大小 [英] Programmatically determine Font-Size for single-line display

查看:120
本文介绍了以编程方式确定单行显示的字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网页上显示文章。文章标题有时会溢出到两行,甚至可能只有一个单词在第二行。这是非常不希望的。使用jQuery / CSS,什么是最好的方法来编程地确定一个新的字体大小为标题保持在一行?

I'm displaying articles on a page. The article titles sometimes spill over onto two lines, and may even have only a single word on the second line. This is very undesirable. Using jQuery/CSS, what would be the best method to programmatically determine a new font-size for the titles to keep them on one line?

推荐答案

种类的黑客,但这样的东西会让你靠近。它可能需要更多的tweeking。基本上,它克隆了元素,并将克隆的文本设置为& nbsp,因此它知道一行的高度是多少。然后它减少元素的字体大小,直到它小于目标高度。

Kind of a hack but: Something like this will get you close. It likely needs a little more tweeking. Basically, it clones the element and sets the clone's text to &nbsp, so it gets an idea of what the height of one line would be. Then it decreases the element's font size until it's smaller than the target height.

请记住,您还需要将此函数附加到父的resize()。

Keep in mind you would also need to attach this function to the parent's resize().

$(document).ready(function() {
    $(".shrink").each(function() {
        var targetHeight = $(this).clone().html(" ").insertAfter($(this));

        while ($(this).height() > targetHeight.height()) {
            $(this).css("font-size", parseInt($(this).css("font-size")) - 1);
        }

        targetHeight.remove();
    });
});

这篇关于以编程方式确定单行显示的字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆