Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...