2017-05-22 4 views
0

J'essaie de limiter le nombre de lignes dans une zone de texte à 20 et le nombre de caractères dans chaque ligne à 15 pour le navigateur IE8. J'ai essayé les solutions déjà disponibles sur stackoverflow comme https://stackoverflow.com/a/11586266/1453499 mais toutes fonctionnent en chrome et d'autres navigateurs modernes non en IE8. Existe-t-il une solution compatible avec IE8?Limitation du nombre de lignes et de lettres sur une seule ligne dans textarea

+0

Changer 'textArea.keypress (fonction (e)' 'à textArea. sur ('keypress change keyup', la fonction (e) 'n'aide pas? –

+0

Cela n'a pas aidé, le problème est avec l'instruction textArea.get (0) .selectionStart – coder

Répondre

0

J'ai utilisé la combinaison de deux réponses (https://stackoverflow.com/a/3373056/1453499 & https://stackoverflow.com/a/11586266/1453499) pour trouver la solution à mon problème, voici la solution finale

function getInputSelection(el) { 
     var start = 0, normalizedValue, range, 
      textInputRange, len, endRange; 

     if (typeof el.selectionStart === "number" && typeof el.selectionEnd === "number") { 
      start = el.selectionStart; 
     } else { 
      range = document.selection.createRange(); 

      if (range && range.parentElement() === el) { 
       normalizedValue = el.value.replace(/\r\n/g, "\n"); 
       len = normalizedValue.length; 

       // Create a working TextRange that lives only in the input 
       textInputRange = el.createTextRange(); 
       textInputRange.moveToBookmark(range.getBookmark()); 

       // Check if the start and end of the selection are at the very end 
       // of the input, since moveStart/moveEnd doesn't return what we want 
       // in those cases 
       endRange = el.createTextRange(); 
       endRange.collapse(false); 

       if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) { 
        start = len; 
       } else { 
        start = -textInputRange.moveStart("character", -len); 
        start += normalizedValue.slice(0, start).split("\n").length - 1; 
       } 
      } 
     } 

     return start; 
    } 

    $(document).ready(function() { 
     //Restrict the search 
     var textArea = $('#textarea_id'); 
     var maxRows = 30; 
     var maxChars = 17; 
     textArea.keypress(function(e) { 
      var text = textArea.val(); 
      var lines = text.split('\n'); 
      if (e.keyCode === 13) { 
       return lines.length < maxRows; 
      } else { //Should check for backspace/del/etc. 
       var caret = getInputSelection(textArea.get(0)); 
       var line = 0; 
       var charCount = 0; 
       $.each(lines, function(i, e) { 
        charCount += e.length; 
        if (caret <= charCount) { 
         line = i; 
         return false; 
        } 
        //\n count for 1 char; 
        charCount += 1; 
       }); 

       var theLine = lines[line]; 
       return theLine.length < maxChars; 
      } 
     }); 

    });