实现一个高度随内容变化,并且支持excel内容复制的输入框

302 阅读1分钟

1、思路由于input框无法实现超出换行,所以要用textarea,然后用一个div标签,添加contenteditable="true"属性,这样div中可以输入内容,并且可以超出换行,也可以把div元素高度顶起来,这样就可以实现自适应的输入框了

2、代码:

html

<form id="box">
    <!-- 高度自适应输入框,可用在from表单中 -->
    <textarea name="" id="first-input"></textarea>
    <!-- 给div添加contenteditable="true"属性 让他变成一个可输入内容的元素 -->
    <div contenteditable="true" id="last-input"></div>
  </form>

style

#box {
    position: relative;
    width: 200px;
    height: 60px;
    margin: 0 auto;
  }
  #first-input {
    padding: 6px;
    font-size: 12px;
    font-family: '微软雅黑';
    width: 100%;
    height: 50%;
    resize:none;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
  }
  #last-input {
    padding: 6px;
    font-size: 12px;
    font-family: '微软雅黑';
    width: 100%;
    height: auto;
    min-height: 50%;
    border: 1px solid;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
  }

script

// 表单输入后给div赋值,使其将自己高度撑起来,然后将高度同步给输入框
    $('#first-input').on('input', function(e) {
      // 赋值excel内容后div赋值的内容不会自动折行, excel的内容折行是用/n实现折行的,所以这里要加个换行下再给div赋值
      $('#last-input').html($(this).val().replace(/\n/g, ''));
      $(this).height($('#last-input').height());
    })