Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
822 views
in Technique[技术] by (71.8m points)

jquery - Programmatically determine Font-Size for single-line display

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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();
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...