2012-07-24 4 views
2

나는 너비가 고정 된 HTML div가 있습니다. 나는 그것에 약간의 텍스트 내용을 넣고 싶다. 텍스트가 너무 길면 텍스트를 자르려고합니다. 그러나 text-overflow: ellipsis 속성과 달리 중간에 잘림을 갖고 싶습니다. 네가 가진 흥미로운 생각을 듣고 싶다.div 너비가 고정되면 중간 잘라내기를 수행하는 가장 좋은 방법은 무엇입니까?

+2

를 표시 할 수 있도록 가치와 거기에서 한 번에 하나의 트림)는

  • 는 사업부에 title 속성을 설정합니다. 절단은 끝에서부터입니다. – stark

  • +0

    단어 (적절한 경우) 또는 문자 만 분리 하시겠습니까? – jonmorgan

    답변

    0

    .substring을 사용하면됩니다. 너비가 10 문자와 줄임표를 더한 값을 가질 수 있다고 가정하면 다음과 같이 할 수 있습니다.

    var myText = "This is a sentence that needs to be reduced"; 
    
    myText = myText.substring(0,5) + "..." + myText.substring(myText.length-5); 
    
    +0

    당신을 위해 그것을 청소. https://jsfiddle.net/jperih/LnaLpz09/ –

    0

    질문은 여기에서 이전에 질문했습니다. 어쩌면 my answer here 더 많은 단서를 제공합니까?

    2

    "테스트"div를 사용하여 값의 크기를 결정하고 원하는 너비에 맞을 때까지 가운데를 트리밍하여 크기를 조정할 수 있습니다.

    jsfiddle example은 대략적인 구현입니다. 그것은/크기 + 생략 컨테이너 폭

    자바 스크립트보다 작을 때까지 한 번에

    // Text excision for generating middle ellipsis values to fit a specific size. 
    
    String.prototype.cutMiddleChar = function() { 
        var charPosition = Math.floor(this.length/2) 
        return this.substr(0, charPosition) + this.substr(charPosition + 1); 
    }; 
    String.prototype.insertMiddleEllipsis = function() { 
        var charPosition = Math.floor(this.length/2) 
        return this.substr(0, charPosition) + '...' + this.substr(charPosition); 
    }; 
    
    var w = 0, 
        t = '', 
        $test = $('.excision-test'); 
    
    $('div').each(function() { 
        // re-usable $this 
        var $this = $(this); 
        // get current width, this is the width we need to fit the value to 
        w = $this.width(); 
        // get current text value, we'll be manipulating this till it's sized right 
        t = $this.text(); 
        // set our test div to the value (plus our ellipsis) for sizing 
        $test.text(t + '...'); 
    
        //console.log(w); 
        //console.log($test.width()); 
    
        // when the value's width is greater than the width of the container loop through to size it down 
        if ($test.width() > w) { 
         while ($test.width() > w) { 
          t = t.cutMiddleChar() 
          //console.log('str cut: ' + t); 
          $test.text(t + '...'); 
          //console.log('str len: ' + t.length); 
          //console.log('width: ' + $test.width()); 
         } 
         $this.text(t.insertMiddleEllipsis()); 
        } 
    });​ 
    

    CSS jQuery를 (비교적 쉽게 따라 개선 할 수있는 일을) 값을 하나 개의 문자를 크기

    /* manipulate font-family, font-size as needed */ 
    body {font-family:arial;font-size:12px;} 
    
    /* div and test div must use same formatting (font-size, font-family, etc) */ 
    div {width:300px;border:1px solid red} 
    .excision-test {position:absolute;left:-10000em;width:auto;} 
    

    HTML

    <div> 
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur vel orci quis nunc vulputate tristique quis id tortor. Donec dui ante, condimentum quis iaculis ut, venenatis vel lorem. Etiam ullamcorper aliquam imperdiet. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Duis tincidunt ligula lorem. Pellentesque pharetra ipsum nec erat tempor vel sagittis libero volutpat. Donec malesuada convallis pharetra. 
    </div> 
    <div class="excision-test"></div>​ 
    

    일반적인 개념은 기능적이지만 특히 페이지에 이러한 값이 많으면 성능이 좋지 않습니다.

    이전

    enter image description here

    일부 추가 고려 사항

    enter image description here

    이이

      하는 것입니다 개선 후
    • 단어가 잘리지 않도록 문자 대신 단어로 자르십시오.
    • 값을 빨리 맞추기 위해 기본 추측을 추가하십시오 (예 : 텍스트의 너비는 1000이고 컨테이너는 100뿐입니다). 호버 툴팁은 여전히 ​​절제 것 전체 가치
    +0

    비슷한 방식으로 작동했습니다. 하지만 'excision-test'div를 사용하는 대신 나는 div에 그것을 사용하고 있었다. 바이올린 예제에 감사드립니다! –

    관련 문제