dynamically changing the size of font size based on text length using css and html

前端 未结 8 1244

I need to display user entered text into a fixed size div. What i want is for the font size to be automatically adjusted so that the text fills the box as much as possible.<

8条回答
  •  庸人自扰
    2020-12-08 04:56

    Getting the size in pixels of a string of text is a hard thing to do and depends a lot on the browser and the user's settings, so it will probably be hard to come up with a solution that works in all cases.

    By "display user entered text" do you mean the user is typing into a textbox? If so, you can attach a keypress listener that checks the length of the value of the text, then adjusts the font-size accordingly. Here's an example, though you will probably need to change the lengths and font-sizes to meet your needs:

    Working Demo

    $('#text').on('keypress', function(e) {
        var that = $(this),
            textLength = that.val().length
        ;
    
        if(textLength > 30) {
            that.css('font-size', '5px');
        } else if(textLength > 20) {
            that.css('font-size', '10px');
        } else if(textLength > 10) {
            that.css('font-size', '15px');
        }
    });
    

提交回复
热议问题