2017-11-30 2 views

Antwort

1

Wie wäre das?

var main = document.querySelector('main'); 
 
var p = document.querySelector('p'); 
 
var stringArr = ['Apple', 'Grape fruit', 'Orange', 'Banana', 'KiwiJuice', 'Tangerine']; 
 

 
function dotdotdot(list){ 
 
    var ix, ixLen, listLen; 
 
    var span = document.createElement('span'); 
 
    span.textContent = ' + '; 
 
    
 
    // 1. insert a text into an element 
 
    // 2. compare the scrollWidth and the clientWidth 
 
    // if scrollWidth is bigger than the other, it means the text has been overflowed 
 
    // 3. find the index of the text which has been overflowed 
 
    // 4. insert <span>+ ?more</span> 
 
    // * when compare two scrollWidths, consider the width of <span> because of the max-width of <main> tag. 
 
    // * the width of <span> is set by 150 px as an example. 
 
    for(ix = 0, ixLen = list.length; ix < ixLen; ix++){ 
 
    if(ix !== ixLen - 1){ 
 
     //main.textContent += list[ix] + ', '; 
 
     p.textContent += list[ix] + ', '; 
 
    }else{ 
 
     //main.textContent += list[ix]; 
 
     p.textContent += list[ix]; 
 
    } 
 
     
 
    if(p.scrollWidth > main.scrollWidth - 150){ 
 
     //p.style.overflow = 'hidden'; 
 
     //p.style.textOverflow = 'ellipsis'; 
 
     p.style.width = p.clientWidth + 'px'; 
 
     
 
     span.textContent += list.length - (ix + 1); 
 
     span.textContent += 'more'; 
 
     main.append(span); 
 
     return; 
 
    } 
 
    } 
 
} 
 

 
dotdotdot(stringArr);
main { 
 
    max-width: 300px; 
 
    height: 30px; 
 
    border: 1px solid #000000; 
 
} 
 

 
p { 
 
    display: inline-block; 
 
    width: fit-content; 
 
    margin: 0; 
 
    white-space: nowrap; 
 
    text-overflow: ellipsis; 
 
    overflow: hidden; 
 
}
<main> 
 
    <p></p> 
 
</main>

+0

Gute Lösung, aber ich werde Zahl Element zählen aus zählen Array mit max-Breite von

Ex:
hat max-width = 400px und Ellipse, Erwartung von mir ist Apple, Orange, Banane, Kiwi ... + 1more ODER Apple, Orange bac mmm yyyyyy ... + 3more 0R 192.168 .56.178-Windows-Server 2012R2 Umgebung ... + 4 mehr –

+0

Mm, ich glaube nicht, dass ich Ihren Standpunkt verstanden habe.So meinst du, wenn die Breite von '

' 400px ist, und dann die Länge der Werte in '
'sollte nicht über'
'überflutet werden, richtig? Wenn es so scheint, sollte '... + 4 mehr' gedruckt werden? – moon

+0

Ja, wenn langer Text in Position 1, oder 2, ... ist zeige 192.168.56.178-W indows server 2012R2 umgebung ... + 4 mehr, wenn der text kürzer ist, wird es zeigen Apple, Orange bac mmm yyyyyy ... + 3mehr nach max-width. –

0

Versuchen Sie, auf Ihrem div mit diesem:

text-overflow: ellipsis; 
+0

Ja, Text-Überlauf: Auslassungs kann ich "abc, xyz ...." zeigen, aber ich möchte zusätzliche Informationen zeigen, ist „abc, xyz, .... + 3 mehr "wenn mein Array 5 Elemente hat :) –

+0

Okay. Sie könnten einfach ein span-Tag wie folgt nach dem Text Ellipse div eingeben: '' – Dave

Verwandte Themen