我正在try 创建一个使用ReactTailwind CSS的注册表.当我将焦点放在一个输入表单上时,标签会向上滑动.在这里之前没有任何问题.然而,当我将焦点放在另一个输入上时,我先前关注的输入的标签变成了占位符.也就是说,向上移动了just的标签返回到其位置.我的代码如下:

<div className="relative mb-4">
              <input
                type="text"
                id="username"
                name="username"
                value={formData.username}
                onChange={handleChange}
                className="peer p-3 h-10 w-full border-b-2 border-gray-300 text-gray-900 placeholder-transparent focus-within:outline-none focus-within:border-rose-600"
                placeholder=""
                required
              />
              <label
                htmlFor="username"
                className={`absolute left-1 top-2 transition-all text-gray-400 ${formData.username.length > 0 ? 'text-md' : 'text-base'
                  } ${formData.username.length > 0 ? 'text-gray-400' : ''
                  } peer-focus-within:left-0 peer-focus-within:-top-6 peer-focus-within:text-gray-700 peer-focus-within:text-md peer-focus-within:text-bold`}
              >
                Username
              </label>
            </div>

截图

First

Second

Third

The problem is here

这个问题在第四个屏幕截图中清晰可见.我怎么才能解决这个问题呢?提前谢谢!

我试图使用模板字符串和三元运算符执行一些判断,但仍然无法解决.

推荐答案

如果我误解了您的问题,请原谅,但您似乎希望标签在用户准备好后停止更改其位置.目前,您更改其位置的效果在

peer-focus-within:-top-6

但当焦点被转移时,问题就来了.在此之后,规则中的焦点将不再适用,取而代之的是原始样式.

解决这个问题的方法很少.我建议您简化样式逻辑以遵循用户名长度,如下所示:

  className={`absolute transition-all ${formData.username.length === 0 ? 'left-1 top-2 text-gray-400 peer-focus-within:left-0 peer-focus-within:-top-6 peer-focus-within:text-gray-700 peer-focus-within:text-md peer-focus-within:text-bold' : 'left-0 -top-6 text-gray-700 text-md text-bold'}`}

转换更改后,类名将永久更改为相同的名称,这样它就不会再更改回来

Css相关问答推荐

如何使搜索框扩展并溢出其他内容

通过使溢出的子元素具有其宽度的100%来防止Flex元素溢出

VueJS CSS动画不会扩展到v-card/v-col之外

如何在Ionic上更改输入的浮点数名称 colored颜色 ?

当面板以Angular 上升时如何定位下拉面板

Css模糊了Chrome中的框边框

如何通过重复的网格区域来简化网格布局?

使元素不水平滚动

包含tailwind 中固定纵横比框的内容

使用 styled-components,我如何定位组件的子类?

Tailwind:如何设置网格的自动填充?

Ant Design:将位置子菜单移动到屏幕顶部

如何在 nth-child 中正确传递 CSS 变量?

如何通过单击
  • 激活 HTML 链接?
  • 表格的边框半径没有按预期工作

    twitter-bootstrap:当鼠标悬停在 -tag 中的 btn-group 上时,如何go 掉带下划线的按​​钮文本?

    使用 CSS3 生成重复的六边形图案

    矩形图像的 CSS 圆形裁剪

    CSS 插入边框

    打印html时在页面上打印页码