移动端页面 输入框怎么实现这种效果??

图片描述

移动端页面怎么实现这种效果? 当输入的文字增加时, 输入框的高度也随着增高, 然后到最高时才开始出现滚动条.
输入框使用input 或者 textarea, 不使用div模拟.

阅读 4.6k
6 个回答

已经解决了. github上有个插件 autosize.js. 大小只有3.6k. 插件地址
使用时设置 height min-height max-height 即可.

友情提示,SF的评论框就是你的需求~

基本思路是动态调整footer的高度:

var ui = {
    footer: document.querySelector('footer'),
    msgInputText: document.querySelector('#msg-text')
}
ui.msgInputText.addEventListener('input', function(event) {
    ui.footer.style.height = ui.msgInputText.scrollHeight + 'px';
});

为什么不用 div 模拟?明明可以用 css 轻松解决的问题,再用 js 去做?

刚入前端时候写的,我把代码复制改了下,没样式,你自己加上去。

<!DOCTYPE html>
<html>
<head>
    <title>xxx</title>
    <meta charset="utf-8">
    <meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimal-ui" />
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        .container{
            position: fixed;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 64px;
            max-height: 300px;
            border-top: 1px solid #ddd;
        }
        .icon1{
            width: 64px;
            height: 64px;
            line-height: 60px;
            position: absolute;
            left: 0;
            bottom: 0;
            text-align: center;
        }
        .icon2{
            width: 64px;
            height: 64px;
            line-height: 60px;
            position: absolute;
            right: 0;
            bottom: 0;
            text-align: center;
        }
        .wrapper{
            height: 100%;
            padding: 2px 64px;
            position: relative;
        }
        .textarea{
            width: 100%;
            height: 30px;
            line-height: 30px;
            max-height: 300px;
            font-size: 18px;
            resize: none;
            border: 1px solid #ddd;
            margin-top: 18px;
        }
    </style>
</head>
<body>
<div class="container" style="background: #FFF;">
    <div class="icon1">Icon1</div>
    <div class="wrapper">
        <textarea id="textarea" class="textarea"></textarea>
    </div>  
    <div class="icon2">Icon2</div>
    <script src="https://cdn.bootcss.com/zepto/1.0rc1/zepto.min.js"></script>
    <script type="text/javascript">
        var areaHeight = $('#textarea').height()
        $('#textarea').on('input propertychange',function(){
            if(areaHeight > 200) {
                return
            }
            var nowHeight = $(this).attr("scrollHeight")
            if(nowHeight !== areaHeight){
                $(this).css('height', nowHeight)
                $('.container').css('height', $('.container').height() + nowHeight - areaHeight)
                areaHeight = nowHeight
            }
        })
    </script>
</div>
</body>
</html>

div 有一个属性,可以变为输入框,高度会随着内容撑起来。css能解决的问题,为何还要用js

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题