You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用CSS实现点击按钮后将其转换为文本框的功能

纯CSS实现「Other按钮转文本框」方案

实现思路

利用原生单选框(radio)的:checked伪类特性,联动标签和文本框的显隐状态,全程不需要额外写JS逻辑,完全满足优先使用CSS的需求,同时兼容原生表单的提交、可访问性规则。

完整代码示例

HTML结构

<form class="option-form">
  <!-- 普通选项示例,剩下3个可以按相同格式补全 -->
  <div class="option-item">
    <input type="radio" name="form-option" id="opt1" value="option1">
    <label for="opt1">Option 1</label>
  </div>
  <div class="option-item">
    <input type="radio" name="form-option" id="opt2" value="option2">
    <label for="opt2">Option 2</label>
  </div>

  <!-- Other选项核心结构 -->
  <div class="option-item">
    <input type="radio" name="form-option" id="opt-other" value="other">
    <label for="opt-other">Other</label>
    <input type="text" name="other-value" class="other-input" placeholder="请输入其他内容">
  </div>
</form>

CSS样式

/* 隐藏原生单选框,保留可选中特性 */
.option-form input[type="radio"] {
  position: absolute;
  opacity: 0;
  pointer-events: none;
}

/* 把label做成按钮样式 */
.option-form label {
  display: inline-block;
  padding: 8px 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  background: #fff;
  cursor: pointer;
  margin-right: 8px;
  margin-bottom: 8px;
}

/* 选中状态的按钮高亮效果 */
.option-form input[type="radio"]:checked + label {
  border-color: #2196F3;
  background: #E3F2FD;
  color: #1976D2;
}

/* 默认隐藏Other的输入框 */
.other-input {
  display: none;
  padding: 8px 16px;
  border: 1px solid #2196F3;
  border-radius: 4px;
  width: 200px;
  /* 和按钮高度保持一致,实现视觉无缝切换 */
  height: 34px;
  box-sizing: border-box;
}

/* 选中Other单选框时,隐藏按钮、显示输入框 */
#opt-other:checked + label {
  display: none;
}
#opt-other:checked ~ .other-input {
  display: inline-block;
  outline: none;
}

补充说明

  • 表单提交时,如果选中非Other选项,直接取form-option的参数值即可;如果选中Other,form-option值为other,同时取other-value的输入值,完全适配原生表单提交逻辑
  • 如果需要点击其他选项时自动清空Other输入框的内容,可以加少量JS实现:
document.querySelectorAll('input[name="form-option"]').forEach(radio => {
  radio.addEventListener('change', () => {
    radio.id !== 'opt-other' && (document.querySelector('.other-input').value = '')
  })
})

内容的提问来源于stack exchange,提问作者TechieInprogress

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 07:51:00