zoukankan      html  css  js  c++  java
  • 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 = ''
        }
      }

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

  • 相关阅读:
    (原创)xcode4的workspace里各lib工程与app工程联编之runscript简介
    使用textmate
    (转)DebuggingTechniques
    (转)ObjectiveC的单例模式(singleton)
    VIA = Via Inner Action
    Das Vergessmichnicht
    Resume
    Explore Subdivide Surface Algorithm Of Maya
    为什么我的文章总是没人回复
    Summer Dream Für Meines Leben
  • 原文地址:https://www.cnblogs.com/chenbeibei520/p/9802545.html
Copyright © 2011-2022 走看看