HTML text-detección de puntos suspensivos de desbordamiento


Tengo una colección de elementos de bloque en una página. Todos tienen las reglas CSS white-space, overflow, text-overflow configuradas para recortar el texto desbordante y usar puntos suspensivos.

Sin embargo, no todos los elementos se desbordan.

¿Puedo usar javascript para detectar qué elementos se desbordan?

Gracias.

Agregado: ejemplo de estructura HTML con la que estoy trabajando.

<td><span>Normal text</span></td>
<td><span>Long text that will be trimmed text</span></td>

Los elementos SPAN siempre caben en las celdas, tienen la regla de puntos suspensivos aplicar. Quiero detectar cuándo se aplican los puntos suspensivos al contenido de texto del INTERVALO.

Author: deanoj, 2011-10-12

11 answers

Érase una vez que necesitaba hacer esto, y la única solución confiable cross-browser que me encontré fue hack job. No soy el mayor fan de soluciones como esta, pero ciertamente produce el resultado correcto una y otra vez.

La idea es que clone el elemento, elimine cualquier ancho de límite y pruebe si el elemento clonado es más ancho que el original. Si es así, sabes que va a haber sido truncado.

Por ejemplo, usando jQuery:

var $element = $('#element-to-test');
var $c = $element
           .clone()
           .css({display: 'inline', width: 'auto', visibility: 'hidden'})
           .appendTo('body');

if( $c.width() > $element.width() ) {
    // text was truncated. 
    // do what you need to do
}

$c.remove();

Hice un jsFiddle para demostrar esto, http://jsfiddle.net/cgzW8/2/

Incluso puedes crear tu propio pseudo-selector personalizado para jQuery:

$.expr[':'].truncated = function(obj) {
  var $this = $(obj);
  var $c = $this
             .clone()
             .css({display: 'inline', width: 'auto', visibility: 'hidden'})
             .appendTo('body');

  var c_width = $c.width();
  $c.remove();

  if ( c_width > $this.width() )
    return true;
  else
    return false;
};

Luego úsalo para encontrar elementos

$truncated_elements = $('.my-selector:truncated');

Demo: http://jsfiddle.net/cgzW8/293 /

Esperemos que esto ayude, hacky como es.

 99
Author: Christian Varga,
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
2015-01-06 06:58:55

Pruebe esta función JS, pasando el elemento span como argumento:

function isEllipsisActive(e) {
     return (e.offsetWidth < e.scrollWidth);
}
 194
Author: Italo Borssatto,
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-04-04 18:57:07

Añadiendo a la respuesta de italo, también puedes hacer esto usando jQuery.

function isEllipsisActive($jQueryObject) {
    return ($jQueryObject.width() < $jQueryObject[0].scrollWidth);
}

También, como Smoky señaló, es posible que desee usar jQuery outerWidth() en lugar de width().

function isEllipsisActive($jQueryObject) {
    return ($jQueryObject.outerWidth() < $jQueryObject[0].scrollWidth);
}
 14
Author: Alex K,
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
2013-10-29 19:06:18

Elem.offsetWdith VS ele.Ancho de desplazamiento Este trabajo para mí! https://jsfiddle.net/gustavojuan/210to9p1 /

$(function() {
  $('.endtext').each(function(index, elem) {
    debugger;
    if(elem.offsetWidth !== elem.scrollWidth){
      $(this).css({color: '#FF0000'})
    }
  });
});
 5
Author: Gustavo Juan,
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
2016-02-08 17:05:18

Este ejemplo muestra información sobre la tabla de celdas con texto truncado. Es dinámico basado en el ancho de la tabla:

$.expr[':'].truncated = function (obj) {
    var element = $(obj);

    return (element[0].scrollHeight > (element.innerHeight() + 1)) || (element[0].scrollWidth > (element.innerWidth() + 1));
};

$(document).ready(function () {
    $("td").mouseenter(function () {
        var cella = $(this);
        var isTruncated = cella.filter(":truncated").length > 0;
        if (isTruncated) 
            cella.attr("title", cella.text());
        else 
            cella.attr("title", null);
    });
});

Demo: https://jsfiddle.net/t4qs3tqs /

Funciona en todas las versiones de jQuery

 4
Author: Red,
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
2015-08-07 07:41:17

La solución más simple (y entre navegadores) es comparar scrollWidth con clientWidth

Código de Trabajo aquí : https://stackoverflow.com/a/19156627/1213445

 4
Author: NicolasBernier,
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
2017-05-23 12:10:45

Para aquellos que usan (o planean usar) la respuesta aceptada de Christian Varga, tenga en cuenta los problemas de rendimiento.

Clonar/manipular el DOM de tal manera causa DOM Reflow (ver una explicación sobre DOM reflow aquí) que es extremadamente intensivo en recursos.

El uso de la solución de Christian Varga en más de 100 elementos en una página causó un retraso de reflujo de 4 segundos durante el cual el hilo JS se bloquea. Teniendo en cuenta que JS es de un solo hilo, esto significa una Retraso de UX para el usuario final.

La respuesta de Italo Borssatto debería ser la aceptada, fue aproximadamente 10 veces más rápida durante mi perfil.

 3
Author: RyanGled,
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
2017-06-08 08:09:21

La respuesta de italo es muy buena! Sin embargo, permítanme refinarlo un poco:

function isEllipsisActive(e) {
   var tolerance = 2; // In px. Depends on the font you are using
   return e.offsetWidth + tolerance < e.scrollWidth;
}

Compatibilidad entre navegadores

Si, de hecho, prueba el código anterior y usa console.log para imprimir los valores de e.offsetWidth y e.scrollWidth, notará, en IE, que, incluso cuando no tiene truncamiento de texto, se experimenta una diferencia de valor de 1px o 2px.

Por lo tanto, dependiendo del tamaño de fuente que utilice, permita una cierta tolerancia!

 1
Author: Andry,
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
2016-02-02 18:12:28

Creo que la mejor manera de detectarlo es usar getClientRects(), parece que cada rect tiene la misma altura, por lo que podemos cacular el número de líneas con el número de diferentes top valor.

getClientRects trabajar como esto

function getRowRects(element) {
    var rects = [],
        clientRects = element.getClientRects(),
        len = clientRects.length,
        clientRect, top, rectsLen, rect, i;

    for(i=0; i<len; i++) {
        has = false;
        rectsLen = rects.length;
        clientRect = clientRects[i];
        top = clientRect.top;
        while(rectsLen--) {
            rect = rects[rectsLen];
            if (rect.top == top) {
                has = true;
                break;
            }
        }
        if(has) {
            rect.right = rect.right > clientRect.right ? rect.right : clientRect.right;
            rect.width = rect.right - rect.left;
        }
        else {
            rects.push({
                top: clientRect.top,
                right: clientRect.right,
                bottom: clientRect.bottom,
                left: clientRect.left,
                width: clientRect.width,
                height: clientRect.height
            });
        }
    }
    return rects;
}

getRowRects trabajar como esto

Puedes detectar como esto

 1
Author: Defims,
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
2016-03-07 09:35:58

Todas las soluciones no funcionaron realmente para mí, lo que hizo fue comparar los elementos scrollWidth con el scrollWidth de su padre (o hijo, dependiendo de qué elemento tenga el disparador).

Cuando el scrollWidth del niño es mayor que sus padres, significa que .text-ellipsis está activo.


Cuando event es el elemento padre

function isEllipsisActive(event) {
    let el          = event.currentTarget;
    let width       = el.offsetWidth;
    let widthChild  = el.firstChild.offsetWidth;
    return (widthChild >= width);
}

Cuando event es el elemento hijo

function isEllipsisActive(event) {
    let el          = event.currentTarget;
    let width       = el.offsetWidth;
    let widthParent = el.parentElement.scrollWidth;
    return (width >= widthParent);
}
 0
Author: Jeffrey Roosendaal,
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
2017-10-20 13:43:28

Con jQuery:

$('#divID').css('text-overflow')

Esto generará su propiedad text-overflow. Así que usted podría comprobar si se trataba de una elipsis con:

if ($('#yourID').css('text-overflow') === 'ellipsis') {
  // It has overflowed
} else {
  // It has not
}
 -1
Author: flamincode,
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-04-20 16:15:22