Insert ellipsis (…) into HTML tag if content too wide

后端 未结 24 3005
名媛妹妹
名媛妹妹 2020-11-22 10:07

I have a webpage with an elastic layout that changes its width if the browser window is resized.

In this layout there are headlines (h2) that will have

24条回答
  •  春和景丽
    2020-11-22 11:08

    This is similar to Alex's but does it in log time instead of linear, and takes a maxHeight parameter.

    jQuery.fn.ellipsis = function(text, maxHeight) {
      var element = $(this);
      var characters = text.length;
      var step = text.length / 2;
      var newText = text;
      while (step > 0) {
        element.html(newText);
        if (element.outerHeight() <= maxHeight) {
          if (text.length == newText.length) {
            step = 0;
          } else {
            characters += step;
            newText = text.substring(0, characters);
          }
        } else {
          characters -= step;
          newText = newText.substring(0, characters);
        }
        step = parseInt(step / 2);
      }
      if (text.length > newText.length) {
        element.html(newText + "...");
        while (element.outerHeight() > maxHeight && newText.length >= 1) {
          newText = newText.substring(0, newText.length - 1);
          element.html(newText + "...");
        }
      }
    };
    

提交回复
热议问题