¿Cómo puedo mostrar puntos ( " ... " ) en un lapso con desbordamiento oculto?


Mi CSS:

#content_right_head span
{
  display:inline-block;
  width:180px;
  overflow:hidden !important;
}

Ahora se muestra content content

Pero quiero mostrar como contenido contenido ...

Necesito mostrar puntos después del contenido. Los contenidos provienen dinámicamente de la base de datos.

Author: angelcool.net, 2012-07-11

7 answers

Para esto puede usar la propiedad text-overflow: ellipsis;. Escribe así

span {
    display: inline-block;
    width: 180px;
    white-space: nowrap;
    overflow: hidden !important;
    text-overflow: ellipsis;
}
<span>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book</span>

JSFiddle

 291
Author: sandeep,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-02 11:25:21

Si está utilizando text-overflow:ellipsis, el navegador mostrará el contenido lo que sea posible dentro de ese contenedor. Pero si desea especificar el número de letras antes de los puntos o eliminar algunos contenidos y agregar puntos, puede usar la siguiente función.

function add3Dots(string, limit)
{
  var dots = "...";
  if(string.length > limit)
  {
    // you can also use substr instead of substring
    string = string.substring(0,limit) + dots;
  }

    return string;
}

Llamar como

add3Dots("Hello World",9);

Salidas

Hello Wor...

Véalo en acción aquí

function add3Dots(string, limit)
{
  var dots = "...";
  if(string.length > limit)
  {
    // you can also use substr instead of substring
    string = string.substring(0,limit) + dots;
  }

    return string;
}



console.log(add3Dots("Hello, how are you doing today?", 10));
 18
Author: kiranvj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-20 05:50:16

Creo que está buscando text-overflow: ellipsis en combinación con white-space: nowrap

Ver más detalles aquí

 13
Author: Ando,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-11 05:51:07

Prueba esto,

.truncate {
    display:inline-block;
    width:180px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

Añade .truncate clase a tu elemento.


EDITAR ,

La solución anterior no funciona en todos los navegadores. puede intentar seguir el plugin jQuery con soporte de navegador cruzado.

(function ($) {
    $.fn.ellipsis = function () {
        return this.eachAsync({
            delay: 100,
            bulk: 0,
            loop: function (index) {
                var el = $(this);

                if (el.data("fullText") !== undefined) {
                    el.html(el.data("fullText"));
                } else {
                    el.data("fullText", el.html());
                }

                if (el.css("overflow") == "hidden") {
                    var text = el.html();
                    var t = $(this.cloneNode(true))
                                        .hide()
                                        .css('position', 'absolute')
                                        .css('overflow', 'visible')
                                        .width('auto')
                                        .height(el.height())
                                        ;

                    el.after(t);

                    function width() { return t.width() > el.width(); };

                    var func = width;
                    while (text.length > 0 && width()) {
                        text = text.substr(0, text.length - text.length * 25 / 100);
                        t.html(text + "...");
                    }

                    el.html(t.html());
                    t.remove();
                }
            }
        });
    };
})(jQuery);

Cómo llamar,

$("#content_right_head span").ellipsis();
 9
Author: Chamika Sandamal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-23 04:14:30

Bueno, el "text-overflow: ellipsis" funcionó para mí, pero solo si mi límite se basaba en 'width', he necesitado una solución que se pueda aplicar en líneas (en el 'height' en lugar del 'width') así que hice este script:

function listLimit (elm, line){
    var maxHeight = parseInt(elm.css('line-Height'))*line;

    while(elm.height() > maxHeight){
        var text = elm.text();
        elm.text(text.substring(0,text.length-10)).text(elm.text()+'...');
    }
}

Y cuando debo, por ejemplo, que mi h3 tiene solo 2 líneas lo hago:

$('h3').each(function(){
   listLimit ($(this), 2)
})

No sé si esa fue la mejor práctica para las necesidades de rendimiento, pero funcionó para mí.

 4
Author: Luís Gustavo Batista,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-20 19:21:07

Puedes probar esto:

.classname{
    width:250px;
    overflow:hidden;
    text-overflow:ellipsis;
}
 2
Author: Kanu Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-29 07:04:12

Muchas gracias @sandeep por su respuesta.

Mi problema fue que quiero mostrar / ocultar texto en span con un clic del ratón. Así que por defecto se muestra texto corto con puntos y al hacer clic aparece texto largo. Al hacer clic de nuevo, se oculta el texto largo y se muestra uno corto de nuevo.

Algo bastante fácil de hacer: simplemente agregue / elimine clase con text-overflow:ellipsis.

HTML:

<span class="spanShortText cursorPointer"  onclick="fInventoryShippingReceiving.ShowHideTextOnSpan(this);">Some really long description here</span>

CSS (lo mismo que @sandeep con .cursorPointer added)

.spanShortText {
  display: inline-block;
  width: 100px;
  white-space: nowrap;
  overflow: hidden !important;
  text-overflow: ellipsis;
}

.cursorPointer {
  cursor: pointer;
}

Parte de jQuery - básicamente solo elimina / añade la clase cSpanShortText.

  function ShowHideTextOnSpan(element) {
    var cSpanShortText = 'spanShortText';
    var $el = $(element);
    if ($el.hasClass(cSpanShortText)) {
      $el.removeClass(cSpanShortText)
    } else {
      $el.addClass(cSpanShortText);
    }
  }
 -1
Author: FrenkyB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-30 08:38:22