복붙노트

[JQUERY] 라인 랩을 찾기

JQUERY

라인 랩을 찾기

해결법


  1. 1.당신은 당신이 (당신이 단락 내부 HTML의 어떤 종류가있는 경우는 큰 수정이 필요합니다) 너무 쓸모 아마 무지하게 간단하고 뭔가를 원한다면 음, 다음이를 보라 :

    당신은 당신이 (당신이 단락 내부 HTML의 어떤 종류가있는 경우는 큰 수정이 필요합니다) 너무 쓸모 아마 무지하게 간단하고 뭔가를 원한다면 음, 다음이를 보라 :

    var para = $('p');
    
    para.each(function(){
        var current = $(this);
        var text = current.text();
        var words = text.split(' ');
    
        current.text(words[0]);
        var height = current.height();
    
        for(var i = 1; i < words.length; i++){
            current.text(current.text() + ' ' + words[i]);
    
            if(current.height() > height){
                height = current.height();
                // (i-1) is the index of the word before the text wraps
                console.log(words[i-1]);
            }
        }
    });
    

    그것은 바로 작동 할 수 있도록 무지 간단합니다. 이것이하는 일은 공백으로 텍스트를 해체 한 후 자동 줄 바꿈을 나타냅니다 요소의 높이의 증가에 대한보고, 말씀으로 말에게 다시 단어를 추가하는 것입니다.

    여기에서보세요 : http://www.jsfiddle.net/xRPYN/2/


  2. 2.PDF 생성과 같은 사용 사례하십시오.

    PDF 생성과 같은 사용 사례하십시오.

    당신은 분할 중간 단어가 발생했을 경우, 적절하게 조정 한 줄에 문자를 제한 할 수 있습니다.

    한 줄 더 정확한 문자를 얻으려면 당신은 허용 각 글꼴에 대한 문자 당 폭을 결정 고정 폭 글꼴을 사용할 수 있습니다. 그리고 허용 된 텍스트 선폭의 크기로 문자 폭을 분할하고, 해당 글꼴의 줄에 허용되는 문자를해야합니다.

    당신은 비 고정 폭 글꼴을 사용할 수 있지만 당신은 각 문자의 폭을 측정해야합니다 - 우. 있는 방법은 폭이 더 마진이나 패딩이없는 범위를 가지고 추측하고 자동화 할 수 있습니다, 그 범위의 폭을 측정하고 그것을 사용하는 각 글꼴 (크기)에 대한 각 문자에 추가 할 수 있습니다.

    나는 코드까지 완료했습니다 :

    /**
     * jQuery getFontSizeCharObject
     * @version 1.0.0
     * @date September 18, 2010
     * @since 1.0.0, September 18, 2010
     * @package jquery-sparkle {@link http://www.balupton/projects/jquery-sparkle}
     * @author Benjamin "balupton" Lupton {@link http://www.balupton.com}
     * @copyright (c) 2010 Benjamin Arthur Lupton {@link http://www.balupton.com}
     * @license Attribution-ShareAlike 2.5 Generic {@link http://creativecommons.org/licenses/by-sa/2.5/
     */
    $.getFontSizeCharObject = function(fonts,sizes,chars){
        var fonts = fonts||['Arial','Times'],
            sizes = sizes||['12px','14px'],
            chars = chars||['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','y','x','z',
                            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','Y','X','Z',
                            '0','1','2','3','4','5','6','7','8','9','-','=',
                            '!','@','#','$','%','^','&','*','(',')','_','+',
                            '[',']','{','}','\\','|',
                            ';',"'",':','"',
                            ',','.','/','<','>','?',' '],
            font_size_char = {},
            $body = $('body'),
            $span = $('<span style="padding:0;margin:0;letter-spacing:0:word-spacing:0"/>').appendTo($body);
    
        $.each(fonts, function(i,font){
            $span.css('font-family', font);
            font_size_char[font] = font_size_char[font]||{};
            $.each(sizes, function(i,size){
                $span.css('font-size',size);
                font_size_char[font][size] = font_size_char[font][size]||{};
                $.each(chars,function(i,char){
                    if ( char === ' ' ) {
                        $span.html('&nbsp;');
                    }
                    else {
                        $span.text(char);
                    }
                    var width = $span.width()||0;
                    font_size_char[font][size][char] = width;
                });
            });
        });
    
        $span.remove();
    
        return font_size_char;
    };
    
    /**
     * jQuery adjustedText Element Function
     * @version 1.0.0
     * @date September 18, 2010
     * @since 1.0.0, September 18, 2010
     * @package jquery-sparkle {@link http://www.balupton/projects/jquery-sparkle}
     * @author Benjamin "balupton" Lupton {@link http://www.balupton.com}
     * @copyright (c) 2010 Benjamin Arthur Lupton {@link http://www.balupton.com}
     * @license Attribution-ShareAlike 2.5 Generic {@link http://creativecommons.org/licenses/by-sa/2.5/
     */
    $.fn.adjustedText = function(text,maxLineWidth){
        var $this = $(this),
            font_size_char = $.getFontSizeCharObject(),
            char_width = font_size_char['Times']['14px'],
            maxLineWidth = parseInt(maxLineWidth,10),
            newlinesAt = [],
            lineWidth = 0,
            lastSpace = null;
    
        text = text.replace(/\s+/g, ' ');
    
        $.each(text,function(i,char){
            var width = char_width[char]||0;
            lineWidth += width;
            if ( /^[\-\s]$/.test(char) ) {
                lastSpace = i;
            }
            //console.log(i,char,lineWidth,width);
            if ( lineWidth >= maxLineWidth ) {
                newlinesAt.push(lastSpace||i);
                lineWidth = width;
                lastSpace = null;
            }
        });
    
        $.each(newlinesAt,function(i,at){
            text = text.substring(0,at+i)+"\n"+text.substring(at+i);
        });
    
        text = text.replace(/\ ?\n\ ?/g, "\n");
    
        console.log(text,newlinesAt);
    
        $this.text(text);
    
        return $this;
    };
    
    $(function(){
        var $body = $('body'),
            $textarea = $('#mytext'),
            $btn = $('#mybtn'),
            $div = $('#mydiv');
    
        if ( $textarea.length === 0 && $div.length === 0 ) {
            $body.empty();
    
            $textarea = $('<textarea id="mytext"/>').val('(When spoken repeatedly, often three times in succession: blah blah blah!) Imitative of idle, meaningless talk; used sometimes in a slightly derogatory manner to mock or downplay another\'s words, or to show disinterest in a diatribe, rant, instructions, unsolicited advice, parenting, etc. Also used when recalling and retelling another\'s words, as a substitute for the portions of the speech deemed irrelevant.').appendTo($body);
            $div = $('<div id="mydiv"/>').appendTo($body);
            $btn = $('<button id="mybtn">Update Div</button>').click(function(){
                $div.adjustedText($textarea.val(),'300px');
            }).appendTo($body);
    
            $div.add($textarea).css({
                'width':'300px',
                'font-family': 'Times',
                'font-size': '14px'
            });
            $div.css({
                'width':'auto',
                'white-space':'pre',
                'text-align':'left'
            });
        }
    
    });
    

  3. 3.여기에 내가 (비판 자유롭게하고 자신의 사악한 목적을 위해 복사)를 사용하여 결국거야.

    여기에 내가 (비판 자유롭게하고 자신의 사악한 목적을 위해 복사)를 사용하여 결국거야.

    편집은 사용자로부터 들어올 때 첫째로, 그것은 (editableElement) .lineText (UserInput 사용자) $와 생겼습니다.

    jQuery.fn.lineText = function (userInput) {
       var a = userInput.replace(/\n/g, " \n<br/> ").split(" ");
       $.each(a, function(i, val) { 
          if(!val.match(/\n/) && val!="") a[i] = '<span class="word-measure">' + val + '</span>';
       });
       $(this).html(a.join(" "));
    };
    

    개행 교체
    태그를 무시 편집 텍스트 상자가 $로 채워집니다 때문에 (editableElement)는 .text ()를, 어떻게,하지만 그들은 여전히 ​​목적을 조판을위한 디스플레이에 다음 줄의 높이를 변경합니다. 이것은 단지 상당히 과일을 낮은 매달려, 초기 목적의 일부가 아니었다.

    나는 형식의 텍스트를 꺼내해야 할 때, 나는 $ 전화 (editableElement) .getLines ()

    jQuery.fn.getLines = function (){
       var count = $(this).children(".word-measure").length;
       var lineAcc = [$(this).children(".word-measure:eq(0)").text()];
       var textAcc = [];
       for(var i=1; i<count; i++){
          var prevY = $(this).children(".word-measure:eq("+(i-1)+")").offset().top;
          if($(this).children(".word-measure:eq("+i+")").offset().top==prevY){
             lineAcc.push($(this).children(".word-measure:eq("+i+")").text());
       } else {
         textAcc.push({text: lineAcc.join(" "), top: prevY});
         lineAcc = [$(this).children(".word-measure:eq("+i+")").text()];
       }
       }
       textAcc.push({text: lineAcc.join(" "), top: $(this).children(".word-measure:last").offset().top});
       return textAcc;
    };
    

    결과적 해시 목록, 한 줄의 텍스트 콘텐츠의 오프셋과 수직을 포함하는 각이다.

    [{"text":"Some dummy set to","top":363},
     {"text":"demonstrate...","top":382},
     {"text":"The output of this","top":420},
     {"text":"wrap-detector.","top":439}]
    

    난 그냥 포맷되지 않은 텍스트를 원하는 경우, $ (editableElement)는 .text () 여전히 반환

    "Some dummy set to demonstrate... The output of this wrap-detector."
    

  4. 4.만약 단락 내의 링크와 같은 좀더 복잡한 구조를 일단 상기 용액 일을하지 않는다 (예를 들어, 사용자가 가질 수 를 내의

    ).

    만약 단락 내의 링크와 같은 좀더 복잡한 구조를 일단 상기 용액 일을하지 않는다 (예를 들어, 사용자가 가질 수 를 내의

    ).

    라인은 이러한 경우에 그 작품을 포장 어디 감지하는 자바 스크립트 라이브러리를 만든 그래서 : http://github.com/xdamman/js-line-wrap-detector

    이게 도움이 되길 바란다.


  5. 5.나는이 기간에 각 라인을 포장해야하는 상황이있다. 나는 텍스트 블록에 패딩 하이라이트 효과를 추가 할 수있는이 정도 않습니다. 텍스트만이 패드 시작과 텍스트 블록의 끝을 감싸는 span 태그의 배경을 추가, 각 행은 개별 포장해야합니다.

    나는이 기간에 각 라인을 포장해야하는 상황이있다. 나는 텍스트 블록에 패딩 하이라이트 효과를 추가 할 수있는이 정도 않습니다. 텍스트만이 패드 시작과 텍스트 블록의 끝을 감싸는 span 태그의 배경을 추가, 각 행은 개별 포장해야합니다.

    이것은 내가 위의 제안에 따라 해낸 것입니다 :

    $.fn.highlghtWrap = function () {
        this.each( function () {
          var current = $( this );
          var text = current.text();
          var words = text.split( ' ' );
          var line = '';
          var lines = [];
    
          current.text( words[ 0 ] );
          var height = current.height();
          line = words[ 0 ];
          for ( var i = 1; i < words.length; i++ ) {
            current.text( current.text() + ' ' + words[ i ] );
    
            if ( current.height() > height ) {
              lines.push( line );
              line = words[ i ];
              height = current.height();
            } else {
              line = line + ' ' + words[ i ];
            }
          }
          lines.push( line );
          current.html( '' );
          $.each( lines, function ( v, a ) {
            current.html( current.html() + '<span>' + a +
              ' </span>' );
          } );
        } );
      }
    
      $( '.home-top_wrapper h2' ).highlghtWrap();
      $( '.home-top_wrapper p' ).highlghtWrap();
    

  6. 6.내부 마크 업 및 임의의 글꼴과 스타일이있을 때 또한 작동하는 개념적으로 간단한 방법은, 간단하게는 자신의 요소 (아마도 'SPAN'또는 'w'와 같은 사용자 지정 이름)에 모든 단어를두고하는 첫 번째 패스를 확인하는 것입니다.

    내부 마크 업 및 임의의 글꼴과 스타일이있을 때 또한 작동하는 개념적으로 간단한 방법은, 간단하게는 자신의 요소 (아마도 'SPAN'또는 'w'와 같은 사용자 지정 이름)에 모든 단어를두고하는 첫 번째 패스를 확인하는 것입니다.

    그럼 당신은 어디에 '최고'속성 변경을 찾기 위해 getBoundingClientRect ()를 사용하여 반복 할 수있다

    function findBreaks() {
        var words = document.getElementsByTagName('w');
        var lastTop = 0;
        for (var i=0; i<words.length; i++) {
            var newTop = words[i].getBoundingClientRect().top;
            if (newTop == lastTop) continue;
            console.log("new line " + words[i].textContent + " at: " + newTop);
            lastTop = newTop;
        }
    }
    

    그것은 천천히 들리 겠지만 문서가 정말 큰 않는 한 당신은 통지하지 않습니다.

  7. from https://stackoverflow.com/questions/3738490/finding-line-wraps by cc-by-sa and MIT license