PHP群:95885625 Hbuilder+MUI群:81989597 站长QQ:634381967
    您现在的位置: 首页 > 开发编程 > JavaScript教程 > 正文

    textarea 高度随内容变化而变化

    作者:admin来源:网络浏览:时间:2021-08-06 15:20:39我要评论
    导读:textarea 高度随内容变化而变化
    一.、通过扩展jQuery      

    html代码

    1. <div style="width: 300px;height: 500px; border: 1px solid red;overflow: scroll;"
    2.     <div id="scoll" class="scroll"
    3.       <div style="width: 300;height: 600px;background-color: greenyellow;"></div> 
    4.     </div> 
    5.   </div> 
    6. </div> 

    JS 代码

    1. $(function () { 
    2.     $.fn.autoHeight = function () { 
    3.       function autoHeight(elem) { 
    4.         elem.style.height = 'auto'
    5.         elem.scrollTop = 0; //防抖动 
    6.         elem.style.height = elem.scrollHeight + 'px'
    7.       } 
    8.       this.each(function () { 
    9.         autoHeight(this); 
    10.         $(this).on('keyup'function () { 
    11.           autoHeight(this); 
    12.         }); 
    13.       }); 
    14.     } 
    15.     $('textarea[autoHeight]').autoHeight(); 
    16.   }) 
    二、直接添加指定元素

    1. <div> 
    2.   <textarea name="" id="" rows="1" oninput="areaChange(this)" style="height: 32px;"></textarea> 
    3. </div> 

    1. function areaChange(_this) { 
    2.     _this.style.height = 'auto'
    3.     _this.scrollTop = 0; //防抖动 
    4.     _this.style.height = _this.scrollHeight + "px" 
    5.  
    6.   } 


    转载请注明(B5教程网)原文链接:https://b5.mxunkeji.com/content-69-6597-1.html
    相关热词搜索: textarea高度