CSS实现输入框宽度随内容自适应效果

  有时候我们会遇到如下需求:输入框的宽度随内容长度自适应,当输入框宽度增大到一定值时,里边的内容自动隐藏。

  面对这种需求,我们首先想到的是使用input元素标签,但是发现input标签的宽度默认设定的是固定的,不支持min-width和max-width样式,所以如果想实现宽度随内容自适应就必须通过js动态修改input元素的样式(width),这样做就会有点麻烦,毕竟很多人更愿意接受只用css就能解决这个问题的方法。如此,HTML中的 contentEditable属性需要了解一下。

  具体代码如下:

// react项目中示例
<div contentEditable="true" class="editable_div" onKeyDown={this.handleKeyDown} />
.editable_div{
        white-space: nowrap;
        overflow-x: hidden;
        display: inline-block;
        font-size: 12px;
        color: #b63f41;
        background-color: #ffffff;
        padding: 2px 8px 2px 4px;
        max-width: 100%;
      }
handleKeyDown = (e) => {
    if (e.keyCode === 13) {
      e.preventDefault()
      const { inputInformationBox } = this.state
      inputInformationBox.push(this.inputValueElem.innerText)
      this.setState({ inputInformationBox }, () => {
        this.scrollWrapElem.scrollTop = this.informationWrapElem.offsetHeight - this.scrollWrapElem.clientHeight
      })
      this.inputValueElem.innerText = ''
    }
  }

这样,我们就可以实现这样的需求啦。

原文地址:https://www.cnblogs.com/chenbeibei520/p/9802545.html