textarea自适应实现

1,988 阅读2分钟

一、背景介绍

在一个老项目中,需要使用到texarea组件,项目久远且庞大,默认的texarea的样式出不来,在一顿查找之后,并没有找到样式出不来的原因,能力和时间都有限,决定单独给texarea写样式并实现高度自适应(即不出现滚动条,高度随内容变化)

二、样式设置

样式就不多说了,直接上代码(借鉴的element-uitextarea样式)

{
    min-height: 54px;
    height: 54px;
    display: block;
    resize: vertical;
    padding: 5px 15px;
    line-height: 1.5;
    box-sizing: border-box;
    width: 100%;
    font-size: inherit;
    color: #606266;
    background-color: #fff;
    background-image: none;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
}

三、高度自适应的思路

要实现自适应高度的几个步骤

  1. 监听textarea内容变化
  2. 计算内容变化后textarea的高度
  3. textarea设置新的高度

四、具体实现

既然有了思路,那就逐个实现吧

  1. 监听内容变化

    // 获取textarea
    const textarea = document.getElementById('myTextarea')
    // 监听内容变化
    textarea.addEventListener('input', function(e) {
    
    })
    

2. 计算内容变化后textarea的高度

textarea的box-sizing 设置为border-box,所以高度应该为内容的高度+上下border的高度

// 监听内容变化
textarea.addEventListener('input', function(e) {

    // 获取textarea的scrollHeight
    const scrollHeight = textarea.scrollHeight

    // 获取textarea的上下边框的高度 
    // 由于textarea的边框可能有别的地方定义了更高级别的样式
    // 使用getComputedStyle 读取的样式是最终样式,包括了内联样式、嵌入样式和外部样式
    // document.defaultView.getComputedStyle(element[,pseudo-element]); 
    // 或者
    // window.getComputedStyle(element[,pseudo-element]);
    const style = getComputedStyle(textarea)

    const borderTop = parseInt(s.borderTopWidth)
    const borderBottom = parseInt(s.borderBottomWidth)
    const height = scrollHeight + borderTop + borderBottom
})

3. 给textarea设置新的高度

    textarea.style.height = height + 'px'

4. 运行代码测试

符合预期效果

四、总结

记录一下自己开发过程中遇到的问题,方便自己以后查看,也希望遇到同样问题的小伙伴可以做个参考,有不足的地方,还请不吝赐教,感谢

在我们的开发过程中,总会遇到这样那样的问题,遇到问题不可怕,只要直面它,找到解决办法,相信你会学到更多的知识