Jquery - эластичное txt поле

Поле для вода текста "ЭЛАСТИЧНОЕ" то есть чем больше текста, тем больше поле можно задать размеры, после чего будет появлятся scrolbar (чтоб не ломался дизайн). Обращайте внимание на комменты в коде
и так начнем первым делом создадим html файл INDEX и в него пишем кодировку и код

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title> НАЗВАНИЕ СТРАНИЦЫ </title>
<script type="text/javascript" src="ext-core/ext-core.js"></script>
<script type="text/javascript" src="elastic-textarea.js"></script>
<style type="text/css">
textarea{
    width: 400px;
    height: 50px;
    border: 3px solid #464646;
    font-family: arial;
    font-size: 14px;
    padding: 5px;
    color:#464646;
}
</style>
</head>
<body>
<h1>ТУТ ТЕКСТ КОТОРЫЙ НАД ТЕКСТОВЫМ ПОЛЕМ ПРОЩЕ ГОВОРЯ ЗАГОЛОВОК</h1><br>
 
<textarea id="foo" >
    ЗДЕСЬ ТОТ ТЕКСТ  КОтОРЫЙ БУДЕТ В ТЕКСТОВОМ ПОЛЕ ДО НАЖАТИЯ ПРИ НАЖАТИИ ОН ИСЧЕЗНЕТ
</textarea>
<script type="text/javascript">
    elasticTextArea("foo");
</script><br>
ТУТ ВАШ ТЕКСТ ТАДАДАДАДА ДАД ТАТАДАДАД (ТЕКСТ ПОД ТЕКСТОВЫМ ПОЛЕМ(МОЖНО СДЕЛАТЬ КАК ФОРМУ КОМЕНТОВ ВСЕ ДОБАВЛЕННЫЕ ТУТ))
 
</body>
</html>

Далее создаем .js файл с именем elastic-textarea внутри пишем(код немой брал с сайта)поэтому коменты нерусские а английский я не так хорошо знаю)
function elasticTextArea (elementId){
 
    /*
     * This are two helper functions, they are delcared here for convinience
     * so we can get and set all styles at once and because they are not available in ext-core
     * only in ExtJs
     */
     
    //available in extjs (not ext-core) as element.getStyles
    function getStyles(el, arguments){
        var ret = {};
        total = arguments.length ;
        for (var n=0; n<total; n++ )
           ret[ arguments[n] ] = el.getStyle(arguments[n]);
        return ret;
    }
   
    //available in extjs (not ext-core) as Ext.Domhelper.applyStyles
    function applyStyles  (el, styles){
        if(styles){
            var i = 0,
                len,
                style;
               
            el = Ext.fly(el);                  
            if(Ext.isFunction(styles)) {
                styles = styles.call();
            }
            if (typeof styles == "string") {
                styles = styles.split(/:|;/g);
                for (len = styles.length; i < len;) {
                    el.setStyle(styles[i++], styles[i++]);  
                }
            } else if (Ext.isObject(styles)) {
                el.setStyle(styles);
            }          
        }  
    }
   
    //minimum and maximum text area size
    var minHeight = 10 ;
    var maxHeight = 300 ;
 
    //increment value when resizing the text area
    var growBy = 20 ;
   
    var el = Ext.get(elementId);
  //get text area width
    var width = el.getWidth();
 
    //current text area styles
    var styles = getStyles(el, ['padding-top', 'padding-bottom', 'padding-left', 'padding-right', 'line-height', 'font-size', 'font-family', 'font-weight', 'font-style']);
 
    //store text area width into styles object to later apply them to the div
    styles.width = width +'px' ;
        //hide the text area scrool to avoid flickering
        el.setStyle('overflow', 'hidden');
      //create the hidden div only if does not exists
        if(! this.div){
 
            //create the hidden div outside the viewport area
            this.div = Ext.DomHelper.append(Ext.getBody() || document.body, {
                'id':elementId + '-preview-div'
                ,'tag' : 'div'
                ,'style' : 'position: absolute; top: -100000px; left: -100000px;'
            }, true);
 
            //apply the text area styles to the hidden div
            applyStyles(this.div, styles);
 
 
            //recalculate the div height on each key stroke
            el.on('keyup', function() {
                elasticTextArea(elementId);
            }, this);
        }
 
      //clean up text area contents, so that no special chars are processed
      //replace \n with <br>&nbsp; so that the enter key can trigger a height increase
      //but first remove all previous entries, so that the height measurement can be as accurate as possible
          this.div.update(
                  el.dom.value.replace(/<br \/>&nbsp;/, '<br />')
                              .replace(/<|>/g, ' ')
                              .replace(/&/g,"&amp;")
                              .replace(/\n/g, '<br />&nbsp;')
                  );
 
          //finally get the div height
          var textHeight = this.div.getHeight();
      //enforce text area maximum and minimum size
          if ( (textHeight > maxHeight ) && (maxHeight > 0) ){
              textHeight = maxHeight ;
              el.setStyle('overflow', 'auto');
          }
          if ( (textHeight < minHeight ) && (minHeight > 0) ) {
              textHeight = minHeight ;
          }
 
          //resize the text area
          el.setHeight(textHeight + growBy , true);
      }

НуНу вот финальная часть создаем папку ext-core и в ней документ ext-core .js название тоже как у папки , внутри пишем (незнаю кто пишет такие большие коды)
Теги:
Jquery, txt, поле
Добавлено: 11 Февраля 2015 20:54:50 Добавил: Андрей Ковальчук Нравится 0
Добавить
Комментарии:
Нету комментариев для вывода...