IT

여러 줄 문자에 줄임표 적용

lottoking 2020. 7. 24. 07:26
반응형

여러 줄 문자에 줄임표 적용


유체 높이 (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/


줄임표 (...)를 한 줄의 텍스트 에 적용하려는 경우 CSS를 사용하면 속성을 사용하여 다소 쉽게 만들 수 있습니다. 여전히 약간의 까다 롭지 만 (모든 요구 사항으로 인해 아래 참조) 가능하고 있습니다.text-overflowtext-overflow

그러나 여기에서와 같이 여러 줄로 된 텍스트에 줄임표를 사용하려는 경우 재미를 기대하지 않습니다. CSS는 해결 방법이 잘못되었습니다.

한 줄 텍스트 줄임표

text-overflow줄임표를 한 줄의 텍스트에 적용 할 수 있습니다. 다음 CSS 요구 사항이 있어야합니다.

  • 이 것 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, 또는 블록 컨테이너 요소보다 다른 것을 사용하고, 줄임표가 비참하게 실패합니다.

여기서 중요한 점 text-overflow: ellipsis은 여러 줄로 된 텍스트에는 영향을 미치지 않습니다 . ( 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가 제거되었으며-link 이제 archive.org에 사본을 참조하지만 이 코드 펜 에서 구현 된 것으로 보입니다 .


여러 줄로 된 텍스트 줄임표는 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>


-webkit-line-clamp를 늘리십시오 . 4; 줄 수를 늘리려면

p {
    display: block;
    display: -webkit-box;
    max-width: 200px;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}
<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>


2018/05/02 편집

라인 준수는 독점적 문서화되지 않은 CSS (웹킷) : https://caniuse.com/#feat=css-line-clamp 는 현재 몇 개의 브라우저에서만 작동합니다.


마침내 내가 원하는 것을 찾을 수있는 해결책을 찾았습니다. pparagraphe와 article래퍼. 당신이 줄임표를 적용 할 경우 p에 따라 article(또한 창 높이에 의존하는) 높이, 당신은 얻을 필요가 heightarticleline-height의를 p다음 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 만 :

.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 및 HTML 솔루션이 있습니다.

이것이 작동하는 방식은 뷰포트의 볼 수있는 영역 아래에 div를 절대적으로 배치하는 것입니다. 콘텐츠가 증가함에 따라 div가 가시 영역으로 업무를 원합니다. 내용이 너무 커지면 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의 현재 상태는 없습니다.

줄임표는 다음 white-space:nowrap을 의미하는 전제 조건 입니다. 줄임표는 한 줄 텍스트 컨테이너에만 그려집니다.


이 공식 사용자 :

overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2; //put number of line here

YouTube가 홈페이지에서 YouTube를 해결하는 방법을보고 단순화했습니다.

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

이렇게하면 2 줄의 코드가 허용되고 줄임표가 추가됩니다.

요점 : https://gist.github.com/eddybrando/386d3350c0b794ea87a2082bf4ab014b


p {
    width:100%;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    background:#fff;
    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>


나는 그것을 위해 내 자신의 해결책을 생각해 봅니다.

/*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)*$/, '...');
            });
        }
    });
}

이것이 당신을 도울 수 있습니다. 툴팁 호버가있는 멀티 라인 타원. 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>

모든 브라우저를 지원하는 적절한 정렬을 순수한 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>

많은 시도 끝에 마침내 다중 라인 및 단일 라인 오버플로를 처리하기 위해 혼합 js / css.

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 코드로 div의 오버플로가 간단히 확인하십시오.

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>

나쁜 CSS는 브라우저 간 멀티 라인 클램핑을 지원하지 웹킷 만이 밀어 넣는 것입니다.

github에서 Ellipsity와 같은 간단한 Javascript 줄임표 라이브러리를 사용하여 소스 코드가 매우 깨끗하고 작기 때문에 추가 변경이 필요한 경우 매우 높은 수준을 유지합니다.

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>

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>

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;
}

자신의 설정을 변경하십시오.


인터넷을 통해보고되는 옵션을 많이 시도한 후에, 그것이 지원을 포함하는지 확인하는 유일한 방법은 자바를 포함하는 것입니다. 나는 여러 줄 잘림이 필요한 게시물 항목을 통과하는 루프 함수를 만들었습니다.

* 참고 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);


이 간단한 방법을 사용합니다. 또한 여기에 jsfiddle 링크가 있습니다.

여기 -webkit-line-clamp중요한 역할이 있습니다. 이 속성의 값은 표시되는 선 수를 결정합니다.

CSS 부분

h3{
      text-align: center;
      overflow: hidden;
      text-overflow: ellipsis;
      margin: 0px 30px;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
   }

HTML 부분

<h3>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. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</h3>

여러 요소가 있고 줄임표 더 많은 버튼이있는 링크가 필요하면 https://stackoverflow.com/a/51418807/10104342를 사용 합니다.

이 같은 것을보고 :

매월 처음 10TB는 청구되지 않습니다. 다른 모든 교통 ... 더 읽기


여러 줄 줄임표를 위해 나를 위해 일하는 내 솔루션 :

.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;
    }
}

장점 :
+ 크로스 브라우저 (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

반응형

'IT' 카테고리의 다른 글

sed : 일치하는 그룹 만 인쇄  (0) 2020.07.24
AngularJS 서비스에 모의 배치  (0) 2020.07.24
대체에서 데이터 유형을 변경하는 방법  (0) 2020.07.24
ReactJS 호출 메소드  (0) 2020.07.24
키워드와 키워드의 차이점  (0) 2020.07.24