programing

다중 행 텍스트에 타원 적용

linuxpc 2023. 9. 8. 21:12
반응형

다중 행 텍스트에 타원 적용

유체 높이(20%)의 div 내부에서 마지막 라인에 타원을 추가할 수 있는 방법이 있습니까?

.-webkit-line-clampCSS에서 작동하지만, 제 경우 라인 번호는 윈도우 크기에 따라 달라집니다.

p {
    width:100%;
    height:20%;
    background:red;
    position:absolute;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.</p>

저는 이 문제를 설명하기 위해 JSFiddle을 가지고 있습니다.https://jsfiddle.net/96knodm6/

-webkit-line-clamp를 늘립니다: 4; 줄 수를 늘리려면:

p {
    display: -webkit-box;
    max-width: 200px;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
<p>Lorem ipsum dolor sit amet, novum menandri adversarium ad vim, ad his persius nostrud conclusionemque. Ne qui atomorum pericula honestatis. Te usu quaeque detracto, idque nulla pro ne, ponderum invidunt eu duo. Vel velit tincidunt in, nulla bonorum id eam, vix ad fastidii consequat definitionem.</p>


라인 클램프는 독점적이고 문서화되지 않은 CSS(웹킷): https://caniuse.com/ #clip=clip-line-clip이므로 현재 몇 개의 브라우저에서만 작동합니다.

중복된 '표시' 속성 제거 + 불필요한 'text-overflow: 생략'을 제거했습니다.

텍스트 한 에 생략(...)을 적용하려면 CSS를 사용하면 속성이 어느 정도 쉬워집니다.(모든 요구 사항으로 인해 – 아래 참조) 아직도 다소 까다롭지만,text-overflow가능하고 신뢰할 수 있게 해줍니다.

그러나 여기 있는 경우처럼 여러 줄로 된 텍스트에 타원을 사용하고 싶다면 재미를 기대하지 마십시오.CSS는 이를 위한 표준 방법이 없으며, 해결 방법은 적중 및 누락됩니다.

한 줄 텍스트에 대한 생략

와 함께text-overflow의 한 할 수 . , 의 에 을 할 할 CSS 사항을:구 CSS을야다음다야구을ese음:gtts

  • 가 있어야만 합니다width,max-width아니면flex-basis
  • 가져야만 한다white-space: nowrap
  • 가져야만 한다overflow가는 이외의 visible
  • 는 합니다.display: block아니면inline-block(또는 플렉스 아이템과 같은 기능적 등가물).

따라서 이 작업이 가능합니다.

p {
  width: 200px;
  white-space: nowrap;
  overflow: hidden;
  display: inline-block;
  text-overflow: ellipsis;
  border: 1px solid #ddd;
  margin: 0;
}
<p>
  This is a test of CSS <i>text-overflow: ellipsis</i>. 
  This is a test of CSS <i>text-overflow: ellipsis</i>. 
  This is a test of CSS <i>text-overflow: ellipsis</i>. 
  This is a test of CSS <i>text-overflow: ellipsis</i>.
  This is a test of CSS <i>text-overflow: ellipsis</i>.
  This is a test of CSS <i>text-overflow: ellipsis</i>.
</p>

jsFiddle 버전

하지만, 제거를 시도해보세요.width, 아니면 그냥 내버려 두거나overflow에의 채무 불이행visible 제거하기, white-space: nowrap요소가 하면, AND,는 비참하게 , 가 을 하는 합니다 하게 은 합니다 하게 은

여기서 한 가지 큰 장점은 다음과 같습니다. 여러 줄로 된 텍스트에는 영향이 없다는 것입니다.(더white-space: nowrap요구사항만으로도 그러한 가능성이 사라집니다.)

p {
    width: 200px;
    /* white-space: nowrap; */
    height: 90px; /* new */
    overflow: hidden;
    display: inline-block;
    text-overflow: ellipsis;
    border: 1px solid #ddd;
    margin: 0;
}
<p>
  This is a test of CSS <i>text-overflow: ellipsis</i>. 
  This is a test of CSS <i>text-overflow: ellipsis</i>. 
  This is a test of CSS <i>text-overflow: ellipsis</i>. 
  This is a test of CSS <i>text-overflow: ellipsis</i>.
  This is a test of CSS <i>text-overflow: ellipsis</i>.
  This is a test of CSS <i>text-overflow: ellipsis</i>.
</p>

jsFiddle 버전


여러 줄 텍스트에 대한 생략

CSS는 다중 줄 텍스트에서 생략에 대한 속성이 없기 때문에 다양한 해결책이 만들어졌습니다.다음과 같은 몇 가지 방법을 찾을 수 있습니다.

위의 Mobify 링크가 제거되어 이제 archive.org 복사본을 참조하지만 이 코드 창에 구현된 것으로 보입니다.

p {
    width:100%;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    background:#fff;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.</p>

이 CSS에서 여러 줄로 된 텍스트를 생략하려면 확인하십시오.

body {
  margin: 0;
  padding: 50px;
}

/* mixin for multiline */
.block-with-text {
  overflow: hidden;
  position: relative;
  line-height: 1.2em;
  max-height: 6em;
  text-align: justify;
  margin-right: -1em;
  padding-right: 1em;
}
.block-with-text:before {
  content: '...';
  position: absolute;
  right: 0;
  bottom: 0;
}
.block-with-text:after {
  content: '';
  position: absolute;
  right: 0;
  width: 1em;
  height: 1em;
  margin-top: 0.2em;
  background: white;
}
<p class="block-with-text">The Hitch Hiker's Guide to the Galaxy has a few things to say on the subject of towels. A towel, it says, is about the most massivelyuseful thing an interstellar hitch hiker can have. Partly it has great practical value - you can wrap it around you for warmth as you bound across the cold moons of  Jaglan Beta; you can lie on it on the brilliant marble-sanded beaches of Santraginus V, inhaling the heady sea vapours; you can sleep under it beneath the stars which shine so redly on the desert world of Kakrafoon;  use it to sail a mini raft down the slow heavy river Moth; wet it for use in hand-to-hand-combat; wrap it round your head to ward off noxious fumes or to avoid the gaze of the Ravenous Bugblatter Beast of Traal (a mindboggingly stupid animal, it assumes that if you can't see it, it can't see you - daft as a bush, but very ravenous); you can wave your towel in emergencies as a distress signal, and of course dry yourself off with it if it still seems to be clean enough. More importantly, a towel has immense psychological value. For some reason, if a strag (strag: non-hitch hiker) discovers that a hitch hiker has his towel with him, he will automatically assume that he is also in possession of a toothbrush, face flannel, soap, tin of biscuits, flask, compass, map, ball of string, gnat spray, wet weather gear, space suit etc., etc. Furthermore, the strag will then happily lend the hitch hiker any of these or a dozen other items that the hitch hiker might accidentally have "lost". What the strag will think is that any man who can hitch the length and breadth of the galaxy, rough it, slum it, struggle against terrible odds, win through, and still knows where his towel is is clearly a man to be reckoned with.</p>

유튜브가 홈페이지에서 어떻게 해결하는지 살펴보고 단순화했습니다.

.multine-ellipsis {
  -webkit-box-orient: vertical;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
}

이렇게 하면 두 줄의 코드가 허용되고 타원이 추가됩니다.

Gist : https://gist.github.com/eddybrando/386d3350c0b794ea87a2082bf4ab014b

제가 하고 싶은 걸 할 수 있는 해결책을 찾았어요.particle p 따라article높이에도 다름),이 창도라름다야를e야 )를 구해야 .heightarticle , , , , , , , , , , , , , , , , , , .line-heightp그리고 나서.articleHeight/lineHeight를의 line-clamp동적으로 추가할 수 있습니다.

은 은입니다.line-heightCSS 파일에 선언해야 합니다.

다음 코드를 확인합니다.,line-clamp 로 하는 을 만드는 .그것을 목표로 하는 플러그인을 만드는 것은 좋을 것입니다.

jsfiddle

function lineclamp() {
  var lineheight = parseFloat($('p').css('line-height'));
  var articleheight = $('article').height(); 
  var calc = parseInt(articleheight/lineheight);
  $("p").css({"-webkit-line-clamp": "" + calc + ""});
}


$(document).ready(function() {
    lineclamp();
});

$( window ).resize(function() {
 	lineclamp();
});
article {
  height:60%;
  background:red;
  position:absolute;
}

p {
  margin:0;
  line-height:120%;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article>
	<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque lorem ligula, lacinia a justo sed, porttitor vulputate risus. In non feugiat risus. Sed vitae urna nisl. Duis suscipit volutpat sollicitudin. Donec ac massa elementum massa condimentum mollis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla sollicitudin sapien at enim sodales dapibus. Pellentesque sed nisl eu sem aliquam tempus nec ut leo. Quisque rutrum nulla nec aliquam placerat. Fusce a massa ut sem egestas imperdiet. Sed sollicitudin id dolor egestas malesuada. Quisque placerat lobortis ante, id ultrices ipsum hendrerit nec. Quisque quis ultrices erat.Nulla gravida ipsum nec sapien pellentesque pharetra. Suspendisse egestas aliquam nunc vel egestas. Nullam scelerisque purus interdum lectus consectetur mattis. Aliquam nunc erat, accumsan ut posuere eu, vehicula consequat ipsum. Fusce vel ex quis sem tristique imperdiet vel in mi. Cras leo orci, fermentum vitae volutpat vitae, convallis semper libero. Phasellus a volutpat diam. Ut pulvinar purus felis, eu vehicula enim aliquet vitae. Suspendisse quis lorem facilisis ante interdum euismod et vitae risus. Vestibulum varius nulla et enim malesuada fringilla. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque lorem ligula, lacinia a justo sed, porttitor vulputate risus. In non feugiat risus. Sed vitae urna nisl. Duis suscipit volutpat sollicitudin. Donec ac massa elementum massa condimentum mollis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla sollicitudin sapien at enim sodales dapibus. Pellentesque sed nisl eu sem aliquam tempus nec ut leo. Quisque rutrum nulla nec aliquam placerat. Fusce a massa ut sem egestas imperdiet. Sed sollicitudin id dolor egestas malesuada. Quisque placerat lobortis ante, id ultrices ipsum hendrerit nec.</p></article>

저는 이 컨셉을 가지고 조금 놀고 있습니다.기본적으로 마지막 캐릭터에서 픽셀 정도가 잘려져도 괜찮으시다면 순수한 css와 html 솔루션이 있습니다.

이 방법은 뷰포트의 보이는 영역 아래에 div를 절대적으로 배치하는 것입니다.우리는 우리의 콘텐츠가 성장함에 따라 디브가 눈에 보이는 영역으로 상쇄되기를 원합니다.콘텐츠가 너무 커지면 디브가 너무 높게 상쇄되기 때문에 콘텐츠의 높이가 올라갈 수 있습니다.

HTML:

<div class="text-container">
  <span class="text-content">
    PUT YOUR TEXT HERE
    <div class="ellipsis">...</div> // You could even make this a pseudo-element
  </span>
</div>

CSS:

.text-container {
    position: relative;
    display: block;
    color: #838485;
    width: 24em;
    height: calc(2em + 5px); // This is the max height you want to show of the text. A little extra space is for characters that extend below the line like 'j'
    overflow: hidden;
    white-space: normal;
}

.text-content {
  word-break: break-all;
  position: relative;
  display: block;
  max-height: 3em;       // This prevents the ellipsis element from being offset too much. It should be 1 line height greater than the viewport 
}

.ellipsis {
  position: absolute;
  right: 0;
  top: calc(4em + 2px - 100%); // Offset grows inversely with content height. Initially extends below the viewport, as content grows it offsets up, and reaches a maximum due to max-height of the content
  text-align: left;
  background: white;
}

Chrome, FF, Safari, IE 11에서 테스트 해봤습니다.

여기에서 확인하실 수 있습니다: http://codepen.io/puopg/pen/vKWJwK

CSS 마법으로 캐릭터의 갑작스러운 단절을 완화할 수도 있습니다.

편집: 이것이 부과하는 한 가지는 단어 깨짐이라고 생각합니다. 그렇지 않으면 콘텐츠가 뷰포트의 맨 끝까지 확장되지 않을 것이기 때문입니다. :(

사람이 해결책이 최고입니다.CSS만:

.multiline-ellipsis {
    display: block;
    display: -webkit-box;
    max-width: 400px;
    height: 109.2px;
    margin: 0 auto;
    font-size: 26px;
    line-height: 1.4;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

유감스럽게도 CSS의 현재 상황은 아닙니다.

조건인 가 에 가 가 있습니다.white-space:nowrap이는 효과적으로 다음을 의미합니다. 타원은 한 줄 텍스트 컨테이너에만 그려집니다.

저는 이를 위해 나름대로 해결책을 생각해 냈습니다.

/*this JS code puts the ellipsis (...) at the end of multiline ellipsis elements
 *
 * to use the multiline ellipsis on an element give it the following CSS properties
 * line-height:xxx
 * height:xxx (must line-height * number of wanted lines)
 * overflow:hidden
 *
 * and have the class js_ellipsis
 * */

//do all ellipsis when jQuery loads
jQuery(document).ready(function($) {put_ellipsisses();});

//redo ellipsis when window resizes
var re_ellipsis_timeout;
jQuery( window ).resize(function() {
    //timeout mechanism prevents from chain calling the function on resize
    clearTimeout(re_ellipsis_timeout);
    re_ellipsis_timeout = setTimeout(function(){ console.log("re_ellipsis_timeout finishes"); put_ellipsisses(); }, 500);
});

//the main function
function put_ellipsisses(){
    jQuery(".js_ellipsis").each(function(){

        //remember initial text to be able to regrow when space increases
        var object_data=jQuery(this).data();
        if(typeof object_data.oldtext != "undefined"){
            jQuery(this).text(object_data.oldtext);
        }else{
            object_data.oldtext = jQuery(this).text();
            jQuery(this).data(object_data);
        }

        //truncate and ellipsis
        var clientHeight = this.clientHeight;
        var maxturns=100; var countturns=0;
        while (this.scrollHeight > clientHeight && countturns < maxturns) {
            countturns++;
            jQuery(this).text(function (index, text) {
                return text.replace(/\W*\s(\S)*$/, '...');
            });
        }
    });
}

아래 코드에서 모든 브라우저를 지원하는 적절한 정렬로 순수한 CSS 트릭을 확인하십시오.

.block-with-text {
    overflow: hidden;
    position: relative;
    line-height: 1.2em;
    max-height: 103px;
    text-align: justify;
    padding: 15px;
}

.block-with-text:after {
    content: '...';
    position: absolute;
    right: 15px;
    bottom: -4px;
    background: linear-gradient(to right, #fffff2, #fff, #fff, #fff);
}
<p class="block-with-text">The Hitch Hiker's Guide to the Galaxy has a few things to say on the subject of towels. A towel, it says, is about the most massivelyuseful thing an interstellar hitch hiker can have. Partly it has great practical value - you can wrap it around you for warmth as you bound across the cold moons of Jaglan Beta; you can lie on it on the brilliant marble-sanded beaches of Santraginus V, inhaling the heady sea vapours; you can sleep under it beneath the stars which shine so redly on the desert world of Kakrafoon; use it to sail a mini raft down the slow heavy river Moth; wet it for use in hand-to-hand-combat; wrap it round your head to ward off noxious fumes or to avoid the gaze of the Ravenous Bugblatter Beast of Traal (a mindboggingly stupid animal, it assumes that if you can't see it, it can't see you - daft as a bush, but very ravenous); you can wave your towel in emergencies as a distress signal, and of course dry yourself off with it if it still seems to be clean enough. More importantly, a towel has immense psychological value. For some reason, if a strag (strag: non-hitch hiker) discovers that a hitch hiker has his towel with him, he will automatically assume that he is also in possession of a toothbrush, face flannel, soap, tin of biscuits, flask, compass, map, ball of string, gnat spray, wet weather gear, space suit etc., etc. Furthermore, the strag will then happily lend the hitch hiker any of these or a dozen other items that the hitch hiker might accidentally have "lost". What the strag will think is that any man who can hitch the length and breadth of the galaxy, rough it, slum it, struggle against terrible odds, win through, and still knows where his towel is is clearly a man to be reckoned with.</p>

아마 이게 여러분들에게 도움이 될 겁니다.툴팁 호버가 있는 여러 줄의 타원입니다.https://codepen.io/Anugraha123/pen/WOBdOb

<div>
     <p class="cards-values">Lorem ipsum dolor sit amet,   consectetur adipiscing elit. Nunc aliquet lorem commodo, semper mauris nec, suscipit nisi. Nullam laoreet massa sit amet leo malesuada imperdiet eu a augue. Sed ac diam quis ante congue volutpat non vitae sem. Vivamus a felis id dui aliquam tempus
      </p>
      <span class="tooltip"></span>
</div>
You can achieve this by a few lines of CSS and JS.

CSS:

        div.clip-context {
          max-height: 95px;
          word-break: break-all;
          white-space: normal;
          word-wrap: break-word; //Breaking unicode line for MS-Edge works with this property;
        }

JS:

        $(document).ready(function(){
             for(let c of $("div.clip-context")){
                    //If each of element content exceeds 95px its css height, extract some first 
                    //lines by specifying first length of its text content. 
                   if($(c).innerHeight() >= 95){
                        //Define text length for extracting, here 170.
                        $(c).text($(c).text().substr(0, 170)); 
                        $(c).append(" ...");
                   }
             }

        });

HTML:

        <div class="clip-context">
            (Here some text)
        </div>

많은 시도 끝에, 저는 마침내 다중 회선과 단일 회선 오버플로를 처리하기 위해 혼합 js/cs를 사용하게 되었습니다.

CSS3 코드:

.forcewrap { // single line ellipsis
  -ms-text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  text-overflow: ellipsis;
  overflow: hidden;
  -moz-binding: url( 'bindings.xml#ellipsis' );
  white-space: nowrap;
  display: block;
  max-width: 95%; // spare space for ellipsis
}

.forcewrap.multiline {
  line-height: 1.2em;  // my line spacing 
  max-height: 3.6em;   // 3 lines
  white-space: normal;
}

.manual-ellipsis:after {
  content: "\02026";      // '...'
  position: absolute;     // parent container must be position: relative
  right: 10px;            // typical padding around my text
  bottom: 10px;           // same reason as above
  padding-left: 5px;      // spare some space before ellipsis
  background-color: #fff; // hide text behind
}

그냥 js 코드로 디브에 오버플로우가 있는지 확인해요, 다음과 같이요.

function handleMultilineOverflow(div) {
    // get actual element that is overflowing, an anchor 'a' in my case
    var element = $(div).find('a'); 
    // don't know why but must get scrollHeight by jquery for anchors
    if ($(element).innerHeight() < $(element).prop('scrollHeight')) {
        $(element).addClass('manual-ellipsis');
    }
}

html의 사용 예:

<div class="towrap">
  <h4>
    <a class="forcewrap multiline" href="/some/ref">Very long text</a>
  </h4>
</div>

CSS3에서 라인 클램프 기능을 사용할 수 있습니다.

p {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    line-height: 25px;
    height: 52px;
    max-height: 52px;
    font-size: 22px;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

설정을 자신의 설정처럼 변경해야 합니다.

CSS가 크로스 브라우저 멀티라인 클램핑을 지원하지 않는다는 것은 유감이지만, 오직 웹킷만이 그것을 밀고 있는 것 같습니다.

깃허브에서 Ellipsity와 같은 간단한 자바스크립트 타원 라이브러리를 사용해 볼 수 있습니다. 소스 코드는 매우 깨끗하고 작기 때문에 추가적인 변경이 필요하다면 꽤 쉬울 것입니다.

https://github.com/Xela101/Ellipsity

<!DOCTYPE html>
<html>
<head>
    <style>
        /* styles for '...' */
        .block-with-text {
            width: 50px;
            height: 50px;
            /* hide text if it more than N lines  */
            overflow: hidden;
            /* for set '...' in absolute position */
            position: relative;
            /* use this value to count block height */
            line-height: 1.2em;
            /* max-height = line-height (1.2) * lines max number (3) */
            max-height: 3.6em;
            /* fix problem when last visible word doesn't adjoin right side  */
            text-align: justify;
            /* place for '...' */
            margin-right: -1em;
            padding-right: 1em;
        }
            /* create the ... */
            .block-with-text:before {
                /* points in the end */
                content: '...';
                /* absolute position */
                position: absolute;
                /* set position to right bottom corner of block */
                right: 0;
                bottom: 0;
            }
            /* hide ... if we have text, which is less than or equal to max lines */
            .block-with-text:after {
                /* points in the end */
                content: '';
                /* absolute position */
                position: absolute;
                /* set position to right bottom corner of text */
                right: 0;
                /* set width and height */
                width: 1em;
                height: 1em;
                margin-top: 0.2em;
                /* bg color = bg color under block */
                background: white;
            }
    </style>
</head>
<body>
    a
    <div class="block-with-text">g fdsfkjsndasdasd asd asd asdf asdf asdf asdfas dfa sdf asdflk jgnsdlfkgj nsldkfgjnsldkfjgn sldkfjgnls dkfjgns ldkfjgn sldkfjngl sdkfjngls dkfjnglsdfkjng lsdkfjgn sdfgsd</div>
    <p>This is a paragraph.</p>

</body>
</html>

인터넷 곳곳을 살펴보고 이 옵션들을 많이 시도한 끝에 자바스크립트를 통해 정확하게 지원되는 것을 확인할 수 있는 유일한 방법은 여러 줄 자르기가 필요한 게시물 항목을 검토하는 루프 기능을 만들었습니다.

*참고로 Jquery를 사용했으며 post_items 클래스에 최대 높이가 고정되어 있어야 합니다.

// loop over post items
$('.post__items').each(function(){
    var textArray = $(this).text().split(' ');
    while($(this).prop('scrollHeight') > $(this).prop('offsetHeight')) {
        textArray.pop();
        $(this).text(textArray.join(' ') + '...');
     }
});
p{
line-height: 20px;
width: 157px;
white-space: nowrap; 
overflow: hidden;
text-overflow: ellipsis;
}

또는 를 사용하고 높이와 오버플로우를 사용하여 라인을 제한할 수 있습니다.

자바스크립트를 사용한다면 아래와 같은 작업을 할 수 있을 것입니다.그러나 이것은 컨테이너의 높이를 고려하지 않습니다.

// whatever string
const myString = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pellentesque sem ut consequat pulvinar. Curabitur vehicula quam sit amet risus aliquet, sed rhoncus tortor fermentum. Etiam ac fermentum nisi. Ut in lobortis eros. Etiam urna felis, interdum sit amet fringilla eu, bibendum et nunc.';

// you can set max string length
const maxStrLength = 100;
const truncatedString = myString.length > maxStrLength ? `${myString.substring(0, maxStrLength)}...` : myString;

console.log(truncatedString);

다중선 타원에 적합한 솔루션은 다음과 같습니다.

.crd-para {
    color: $txt-clr-main;
    line-height: 2rem;
    font-weight: 600;
    margin-bottom: 1rem !important;
    overflow: hidden;

    span::after {
        content: "...";
        padding-left: 0.125rem;
    }
}

요소도 여러 개 있는데 생략 후에 읽기 버튼이 더 있는 링크를 원한다면 https://stackoverflow.com/a/51418807/10104342 에서 확인해 보십시오.

이런 것을 원하신다면:

매월 처음 10TB는 충전되지 않습니다.다른 교통은 다...더 읽기

장점:
+ 크로스 브라우저 (IE11, Edge, Chrome, Firefox, Safari 등)
+ 가장 자연스러운 모습

단점:
- DOM에 추가 요소를 많이 추가합니다.

저는 제가 본 어떤 해결책에도 만족하지 않았습니다.대부분 현재 웹킷에서만 지원되는 라인클램프를 사용합니다.그래서 해결책이 나올 때까지 가지고 놀았습니다.이 순수 자바스크립트 솔루션은 IE10 이상 및 모든 최신 브라우저와 호환되어야 합니다.아래 스택 오버플로 예제 공간 외부에서는 테스트되지 않았습니다.

저는 이것이 좋은 해결책이라고 생각합니다.한 가지 큰 주의 사항은 컨테이너 내부에 각 단어에 대한 간격이 생겨 배치 성능에 영향을 미치므로 주행 거리가 달라질 수 있다는 것입니다.

//This is designed to be run on page load, but if you wanted you could put all of this in a function and addEventListener and call it whenever the container is resized.
var $container = document.querySelector('.ellipses-container');

//optional - show the full text on hover with a simple title attribute
$container.title = $container.textContent.trim();

$container.textContent.trim().split(' ').some(function (word) {
  //create a span for each word and append it to the container
  var newWordSpan = document.createElement('span');
  newWordSpan.textContent = word;
  $container.appendChild(newWordSpan);
  
  if (newWordSpan.getBoundingClientRect().bottom > $container.getBoundingClientRect().bottom) {
    //it gets into this block for the first element that has part of itself below the bottom of the container
    //get the last visible element
    var containerChildNodes = $container.childNodes;
    var lastVisibleElement = containerChildNodes[containerChildNodes.length - 2];
    
    //replace this final span with the ellipsis character
    newWordSpan.textContent = '\u2026';
    
    //if the last visible word ended very near the end of the line the ellipsis will have wrapped to the next line, so we need to remove letters from the last visible word
    while (lastVisibleElement.textContent != "" && newWordSpan.getBoundingClientRect().bottom > $container.getBoundingClientRect().bottom) {
      lastVisibleElement.style.marginRight = 0;
      lastVisibleElement.textContent = lastVisibleElement.textContent.slice(0, -1);
    }
    
    //using .some() so that we can short circuit at this point and no more spans will be added
    return true;
  }
});
.multi-line-container {
  border: 1px solid lightgrey;
  padding: 4px;
  height: 150px;
  width: 300px;
}

.ellipses-container {
  display: inline-flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-content: flex-start; /* optionally use align-content:stretch, the default, if you don't like the extra space at the bottom of the box if there's a half-line gap */
  overflow: hidden;
  position: relative;
}

.ellipses-container > span {
  flex: 0 0 auto;
  margin-right: .25em;
}

.text-body {
  display: none;
}
<div class="multi-line-container ellipses-container">
  <div class="text-body ellipses-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque luctus ut massa eget porttitor. Nulla a eros sit amet ex scelerisque iaculis nec vitae turpis. Sed pharetra tincidunt ante, in mollis turpis consectetur at. Praesent venenatis pulvinar lectus, at tincidunt nunc finibus non. Duis tortor lectus, elementum faucibus bibendum vitae, egestas bibendum ex. Maecenas vitae augue vitae dui condimentum imperdiet sit amet mattis quam. Duis eleifend scelerisque magna sed imperdiet. Mauris tempus rutrum metus, a ullamcorper erat fringilla a. Suspendisse potenti. Praesent et mi enim. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
  </div>
</div>

언급URL : https://stackoverflow.com/questions/33058004/applying-an-ellipsis-to-multiline-text

반응형