2009-11-12 11 views
10

Posso nascondere il testo in un DIV dopo un numero di caratteri con jQuery?testo limite jquery per lunghezza

Finora penso che sarebbe andata qualcosa di simile - jQuery passerebbe in rassegna il testo fino a raggiungere un certo numero di caratteri. Dovrebbe quindi avvolgere un DIV da quella posizione alla fine del testo che potrebbe quindi essere nascosto con il metodo hide(). Non sono sicuro di come inserire quel testo di avvolgimento.

Un altro modo per aggirare questo sarebbe anche apprezzato.

Grazie.

+0

Hai menzionato in un commento qui sotto che il contenuto che stai cercando di limitare potrebbe contenere tag di testo e HTML. I tag sono standardizzati o hai bisogno di una soluzione dinamica? Inoltre ... ci saranno più tag figlio con testo in ciascuno? Penso che quelli siano fattori importanti. – jessegavin

+0

Penso che i soli tag con il testo saranno i tag
. – usertest

+0

Si potrebbe desiderare di guardare le risposte [qui] (http://stackoverflow.com/questions/536814/javascript-insert-ellipsis-into-html-tag-if-content-too-wide). – Paddy

risposta

10

In questo modo nascondere una parte del testo

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 

    <title>untitled</title> 
    <style type="text/css" media="screen"> 
     .hide{ 
      display: none; 
     } 
    </style> 
    <script src="js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> 
    <script type="text/javascript" charset="utf-8"> 
     $(function(){ 
      var $elem = $('p');   // The element or elements with the text to hide 
      var $limit = 10;  // The number of characters to show 
      var $str = $elem.html(); // Getting the text 
      var $strtemp = $str.substr(0,$limit); // Get the visible part of the string 
      $str = $strtemp + '<span class="hide">' + $str.substr($limit,$str.length) + '</span>'; // Recompose the string with the span tag wrapped around the hidden part of it 
      $elem.html($str);  // Write the string to the DOM 
     }) 
    </script> 

</head> 
<body> 
<p>Some lenghty string goes here</p> 
</body> 
</html> 
+0

Ciao grazie per la risposta, ma ha lo stesso problema del codice di jessegavin, i tag HTML non vengono ignorati. Quindi a volte la metà di un tag si presenta nell'output. – usertest

+1

Non riesco a commentare la risposta di jessegavin, ma ecco il modo di farlo funzionare in più div: Metti il ​​codice jQuery all'interno di questo: $ ('. SomeClass'). Each (function() {// Code goes here}); e apporta la modifica: "#myDiv" A questo – zyON

+0

Grazie, finalmente ha funzionato. – usertest

0

Se si inserisce un gestore di eventi onkeydown sul tag del corpo, è possibile conteggiare la lunghezza nel div di interesse, quindi è possibile nasconderlo al termine e rimuovere il gestore di eventi.

1

Sto sostituendo la mia risposta originale con questo .....

<html> 
<head> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<script type="text/javascript"> 
    $(function() { 
     var limit = 20; 
     var chars = $("#myDiv").text(); 
     if (chars.length > limit) { 
      var visiblePart = $("<span> "+ chars.substr(0, limit-1) +"</span>"); 
      var dots = $("<span class='dots'>... </span>"); 
      var hiddenPart = $("<span class='more'>"+ chars.substr(limit-1) +"</span>"); 
      var readMore = $("<span class='read-more'>Read More</span>"); 
      readMore.click(function() { 
       $(this).prev().remove(); // remove dots 
       $(this).next().show(); 
       $(this).remove(); // remove 'read more' 
      }); 

      $("#myDiv").empty() 
       .append(visiblePart) 
       .append(dots) 
       .append(readMore) 
       .append(hiddenPart); 
     } 
    }); 
</script> 
<style type="text/css"> 
    span.read-more { cursor: pointer; color: red; } 
    span.more { display: none; } 
</style> 
</head> 
<body> 
    <div id="myDiv">Here are all<br/> my characters.<br/> I would like to limit them to 20.</div> 
</body> 
</html> 
+1

La tua variabile 'len' è un po 'in sospeso =) – BalusC

+0

Ciao, grazie, ma sfortunatamente il testo DIV contiene tag HTML perché ottengo da un'API esterna. – usertest

+0

Per quanto posso dire ci sono solo tag
nel mio testo, c'è un modo per saltarli nel tuo codice? Grazie. – usertest

2

Jeff ho avuto lo stesso problema voluto aggiungere il limitatore di testo a un contenuto dinamico ecco quindi la mia soluzione:

// TEXT CHARACTER LIMITER 

$(document).ready(function() { 

    $.fn.textlimit = function() 
    { 

    return this.each(function()      
    { 

    var $elem = $(this);   // Adding this allows u to apply this anywhere 
    var $limit = 22;    // The number of characters to show 
    var $str = $elem.html();  // Getting the text 
    var $strtemp = $str.substr(0,$limit); // Get the visible part of the string 
    $str = $strtemp + '<span class="hide">' + $str.substr($limit,$str.length) + '</span> ...'; 
    $elem.html($str); 
    }) 

    }; 

}); 

// Call the text limiter above 

$(document).ready(function() { 

    $('.someGenericClass .anotherClass').textlimit() 

}); 
21

Penso che lo scopo possa essere risolto molto più easie r modo che spiegato sopra

$(function(){ 
    $(".title").each(function(i){ 
    len=$(this).text().length; 
    if(len>10) 
    { 
     $(this).text($(this).text().substr(0,10)+'...'); 
    } 
    });  
}); 

Il codice jQuery sopra sarà nascondere il testo div se supera 10 caratteri così come annunci ... alla fine per spiegare che c'è qualcosa di più.

+0

Sono passato a questo dalla risposta, poiché avevo solo bisogno che fosse applicata SE il limite di testo ha colpito. Anche questo è meno codice. Grazie per questa bella risposta +1 – Doidgey

+0

aggiungi un ritaglio() per il testo difficile. –

+0

che dire quando si lavora con wordpress? Ho provato questa funzione per limitare la classe span 'rs_rs_name' a 45 caratteri, ma non funziona .. qualche idea? 'jQuery (function() { jQuery ("rs_rs_name".) Ciascuno (function (i) { len = $ (this) .text() lunghezza;.. se (len> 45) { jQuery (this) .text ($ (this) .text(). substr (0,45) + '...'); } }); }); ' – RobBenz

1
$.fn.textlimit = function(limit) 
{ 
    return this.each(function(index,val)      
    { 
     var $elem = $(this); 
     var $limit = limit; 
     var $strLngth = $(val).text().length; // Getting the text 
     if($strLngth > $limit) 
     { 
      $($elem).text($($elem).text().substr(0, $limit)+ "..."); 
     } 
    }) 
}; 

**how to use** 

$("#DivId").textlimit(60); 
Problemi correlati