2015-08-01 3 views
0

Я ищу автоматическое изменение размера шрифта для каждой новой строки равной ширины для многострочного редактируемого текстового поля. Пожалуйста, проверьте ниже URL:Автоматическое изменение размера многострочного редактируемого текстового поля в JQuery

http://api.pstr.co/html/template/003_script

Сейчас размер шрифта, как этот

enter image description here

, и я хочу быть похожим на что:

enter image description here

Код jquery для этого плагина таков:

function getBaseFontSize(){ 
     var baseFontSize = Math.round(0.15*Math.min($(window).width(), $(window).height())); 
     return baseFontSize; 
    } 


    function editModeSetup(){ 
     var contentBlock = $(".content"); 
     var container = $(".block"); 
     var scalableText = $(".scalable"); 

     $('[contenteditable]').each(function (index) { 
      var $this = $(this); 

      $this 
      .on("keydown", function(){ 
       clearTimeout($this.timeout); 
       fitTextMultiline(scalableText,contentBlock,container); 
       //if (!$this.hasClass("edited")) $(this).addClass("edited"); 

      }).on("focus", function() { 

        //if (!$this.hasClass("edited")){ 
         $this.selectText(); 
        //} 

        // Work around Chrome's little problem 
        $this.mouseup(function() { 
           // Prevent further mouseup intervention 
           $this.unbind("mouseup"); 
           return false; 
        }); 

      }).on("keyup", function() { 

       $this.timeout = setTimeout(function(){ fitTextMultiline(scalableText,contentBlock,container); }, 400); 
      }); 


     //$(".content").css("font-size", getBaseFontSize()); 
     $("html").css("font-size", getBaseFontSize()); 

     }); 

     fitTextMultiline(scalableText,contentBlock,container); 

     $(window).resize(function() { 
      fitTextMultiline(scalableText,contentBlock,container);  
     }); 

     var myWidth = window.innerWidth; 
     var myHeight = window.innerHeight; 

      ga('send', 
      'event', 
      'Viewport', 
      'Size', 
      myWidth+'x'+myHeight, 
      {'nonInteraction': 1}); 


    } 


    function fitTextMultiline(scalableText, contentBlock, container) { 
     // startvwith small type and push the size up? to make sure more fits on one line... 
     var maxHeight = container.height(); 
     var maxWidth = container.width(); 
     //console.log(".\n") 
     //console.log(scalableText.text()) 
     var fontSize = 7*getBaseFontSize(); // 20; 
     var fontUnits = "px"; // "vmin"; 

     do { 
      scalableText.css('font-size', fontSize+fontUnits); 
      contentHeight = contentBlock.height(); 
      contentWidth = contentBlock.width(); 
      //console.log("--- " + fontSize +" ---") 
      //console.log(contentHeight + " ? " + maxHeight) 
      //console.log(contentWidth + " ? " + maxWidth) 
      fontSize = Math.round(fontSize - fontSize*0.1); 

     } while ((contentHeight > maxHeight || contentWidth > maxWidth ) && fontSize > 10); 
    //+ fontSize/2 


     alignPrices(); 
     doubleLineAssignClasses(); 
     return this; 
    } 


    // code that returns text from edit mode 

    function getPosterText() { 
    /* 
     (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ 
     (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), 
     m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) 
     })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); 

     ga('create', 'UA-61477423-5', 'auto'); 
     ga('send', 'pageview'); 
    */ 
     ga('send', 'event', 'Button', 'Save', document.title); 

     var list = $('[contenteditable]').map(function() { 
      //console.log($(this).text()); 
      //console.log($(this).val()); 
      //console.log(_jsonEscape($(this).val())); 

      //return $(this).text(); 
      return $(this).html(); 
     }).toArray(); 

     return _jsonEscape(JSON.stringify(list)); 
    } 

    // code that sets text in edit mode 


    function setPosterText(text) { 


    /* 
     var list; 

     console.log(text) 
     try { 
      list = JSON.parse(text) 
     } 
     catch (e) { 
      console.log('Cannot parse given texts json.'); 
      list = []; 

     } 
    */ 
     //if (list.length > 0) 

      /* 
      $('[contenteditable]').each(function (index) { 
       //$(this).text(list[index] || ""); 
       $(this).addClass("userText") 
      }); 
     */ 

     //var contentBlock = $(".content"); 
     //var container = $(".block"); 
     //var scalableText = $(".scalable"); 

     //fitTextMultiline(scalableText,contentBlock,container); 

    } 

    function _jsonEscape(str) { 

     //str = str.replace(/&/g,"&").replace(/£/g,"£"); 
     //str.replace(/£/g,"£"); 
     return str.replace(/\\n/g, "\\\\n").replace(/\\r/g, "\\\\r").replace(/\\t/g, "\\\\t"); 

    } 

    function editableListFix(){ 
     $('ul').on('keyup keydown', function() { 
     var $this = $(this); 
     if (! $this.html()) { 
      var $li = $('<li></li>'); 
      var sel = window.getSelection(); 
      var range = sel.getRangeAt(0); 
      range.collapse(false); 
      range.insertNode($li.get(0)); 
      range = range.cloneRange(); 
      range.selectNodeContents($li.get(0)); 
      range.collapse(false); 
      sel.removeAllRanges(); 
      sel.addRange(range); 

     } else { 
      //are there any tags that AREN'T LIs? 
      //this should only occur on a paste 
      var $nonLI = $this.find(':not(li, br)'); 

      if ($nonLI.length) { 
       $this.contents().replaceWith(function() { 
     //we create a fake div, add the text, then get the html in order to strip out html code. we then clean up a bit by replacing nbsp's with real spaces 
    return '&lt;li&gt;' + $('&lt;div /&gt;').text($(this).text()).html().replace(/&nbsp;/g, ' ') + '</li>'; 
       }); 
       //we could make this better by putting the caret at the end of the last LI, or something similar 
      }     
     } 
    }); 
    } 



    function alignPricesFix(){ 
     alignPrices() 


     $('[contenteditable]').each(function (index) { 
      var $this = $(this); 

      $this 
      .on("keyup keydown", function(){ 
       alignPrices(); 
      }); 
     }); 
    } 

    function alignPrices(){ 
     var positions = []; 
     var heights = []; 
     $(".items>li").each(function(index) { 
      positions.push($(this).position().top); 
      heights.push($(this).height()); 
     }); 

     $(".prices>li").each(function(index) { 
      //$(this).css("top", positions[index]); 
      $(this).css("height", heights[index]); 
     }); 

     ulPrices = $("ul.prices"); 
     if (ulPrices) ulPrices.css("height", $("ul.items").height()); 

    } 

    function doubleLineAssignClasses(){ 
     $(".double-line>li").each(function(index) { 
      $(this).removeClass('item-header'); 
      $(this).removeClass('item-description'); 

      //if (!$(this).hasClass('item-header') && !$(this).hasClass('item-description')){ 
      if (index % 2 != 1) $(this).addClass('item-header') 
      else $(this).addClass('item-description') ; 
       //console.log(index); 

     }); 


    } 

ответ

0

проверить этот сайт для JQuery/JavaScript решения https://css-tricks.com/forums/topic/is-it-possible-to-adapt-font-size-to-div-width/

я цитирую его здесь также: «Эй, это не будет достижимо с только CSS, но вы могли бы, конечно, сделать это с помощью JQuery/JavaScript. Например, вы можете заключить каждое слово в диапазон, измерить ширину этого диапазона, разделить ширину родительского div на ширину диапазона, а затем умножить размер шрифта текста диапазона на это число.

i.e: (ширина ширины/ширины пролета) * размер шрифта span "

Смежные вопросы