Skip to content

Instantly share code, notes, and snippets.

@Houserqu
Created May 5, 2021 01:51
Show Gist options
  • Save Houserqu/cea3367aee9b4407189c84e5e8ff7b13 to your computer and use it in GitHub Desktop.
Save Houserqu/cea3367aee9b4407189c84e5e8ff7b13 to your computer and use it in GitHub Desktop.
textarea自适应

实现原理:textarea本身并不会随着文本高度而增高。给textarea套上外容器,使用绝对定位,设置height:100%; width:100%; 这样textarea就可以随着外容器的高度变化而变化。再利用块级元素填充文字,块元素可以随着文本高度自动增高。设置块元素visibility: hidden;样式与textarea一致即可。 https://juejin.im/post/6844903682266529805

<Container>
  <div className='text'>
	  <div className='hidden'>{decodeText}</div>
	  <Input
	    className='textarea'
	    disabled
	    multiline
	    size="full"
	    placeholder="decode 后文本"
	    value={decodeText}
	  />
	</div>
</Container>

const Container = styled.div`
  .text {
    position: relative;
    width: 100%;

    .hidden {
      width: 100%;
      min-height: 50px;
      white-space: pre-wrap;
      visibility: hidden;
      word-wrap: break-word;
      word-break: break-word;
    }

    .textarea {
      min-height: 50px;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      resize: none;
    }
  }
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment