Calculate text width with JavaScript

前端 未结 24 1688
陌清茗
陌清茗 2020-11-21 05:08

I\'d like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?

If it\'s not built-in, my only idea is t

24条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 05:43

    The code-snips below, "calculate" the width of the span-tag, appends "..." to it if its too long and reduces the text-length, until it fits in its parent (or until it has tried more than a thousand times)

    CSS

    div.places {
      width : 100px;
    }
    div.places span {
      white-space:nowrap;
      overflow:hidden;
    }
    

    HTML

    This is my house
    And my house are your house
    This placename is most certainly too wide to fit

    JavaScript (with jQuery)

    // loops elements classed "places" and checks if their child "span" is too long to fit
    $(".places").each(function (index, item) {
        var obj = $(item).find("span");
        if (obj.length) {
            var placename = $(obj).text();
            if ($(obj).width() > $(item).width() && placename.trim().length > 0) {
                var limit = 0;
                do {
                    limit++;
                                        placename = placename.substring(0, placename.length - 1);
                                        $(obj).text(placename + "...");
                } while ($(obj).width() > $(item).width() && limit < 1000)
            }
        }
    });
    

提交回复
热议问题