Truncate text with jQuery based on pixel width

前端 未结 5 1896
梦谈多话
梦谈多话 2020-12-08 05:48

I\'m trying to use jquery to write a fast function that calculates the pixel width of a string on a html page, then truncates the string until it reaches an ideal pixel widt

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 06:36

    The function takes the text to check, the ideal_width in pixel and the class name for the css. If the ideal_width is less than the text width it truncs and adds the hellip otherwise it returns the text unmodified. Simple and works! :-)

    function constrain(text, ideal_width, className){
    
        var temp_item = ('');
        $(temp_item).appendTo('body');
        var item_width = $('span.'+className+'_hide').width();
        var ideal = parseInt(ideal_width);
        var smaller_text = text;
    
        if (item_width>ideal_width){
            while (item_width > ideal) {
                smaller_text = smaller_text.substr(0, (smaller_text.length-1));
                $('.'+className+'_hide').html(smaller_text);
                item_width = $('span.'+className+'_hide').width();
            }
            smaller_text = smaller_text + '…'
        }
        $('span.'+className+'_hide').remove();
        return smaller_text;
    }
    

提交回复
热议问题