Truncate text with jQuery based on pixel width

前端 未结 5 1895
梦谈多话
梦谈多话 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:24

    Thanks, I got it working - but it only works on the first item and stops, does this have to do with the way I'm declaring variables?

    here's the current code:

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

提交回复
热议问题