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

如何实现仅点击按钮后才显示<input>输入框的功能?

输入框显隐控制实现方案

以下是不同技术栈下的可落地实现方式:

原生HTML/CSS/JS实现(无框架依赖)

实现逻辑

默认给输入框加隐藏样式,监听指定按钮的点击事件,触发时移除隐藏样式、添加显示样式即可。

  • HTML 结构代码:
<!-- 触发显示的自定义按钮 -->
<button id="startTypeBtn">开始打字挑战</button>
<!-- 输入框默认携带隐藏类 -->
<input id="gameInput" class="input-hide" type="text" placeholder="输入对应文字">
  • CSS 样式代码:
/* 默认隐藏样式,不占页面布局空间 */
.input-hide {
  display: none;
}
/* 显示状态样式,可按需调整适配移动端 */
.input-show {
  display: block;
  width: 92%;
  margin: 12px auto;
  padding: 10px;
  font-size: 16px; /* 避免iOS Safari自动放大页面 */
  border-radius: 4px;
  border: 1px solid #eee;
}
  • JS 交互代码:
const startBtn = document.getElementById('startTypeBtn')
const gameInput = document.getElementById('gameInput')

startBtn.addEventListener('click', function() {
  // 切换为显示状态
  gameInput.classList.remove('input-hide')
  gameInput.classList.add('input-show')
  // 可选:自动唤起移动端软键盘,优化体验
  gameInput.focus()
})

主流前端框架简化实现

如果你的项目使用了前端框架,可以直接通过框架的条件渲染能力实现,代码更简洁:

  • Vue 3 示例:
<template>
  <button @click="isInputShow = true">开始打字挑战</button>
  <input v-if="isInputShow" v-model="typeContent" type="text" placeholder="输入对应文字" />
</template>
<script setup>
import { ref } from 'vue'
// 默认值为false,输入框默认隐藏
const isInputShow = ref(false)
const typeContent = ref('')
</script>
  • React 示例:
import { useState } from 'react'

function GameHomePage() {
  // 默认值为false,输入框默认隐藏
  const [isInputShow, setIsInputShow] = useState(false)
  const [typeContent, setTypeContent] = useState('')

  return (
    <>
      <button onClick={() => setIsInputShow(true)}>开始打字挑战</button>
      {isInputShow && (
        <input 
          type="text" 
          value={typeContent}
          onChange={(e) => setTypeContent(e.target.value)}
          placeholder="输入对应文字"
        />
      )}
    </>
  )
}

移动端适配注意事项

  • 输入框字体设置为16px及以上,可以避免iOS Safari触发自动放大页面的默认逻辑
  • 唤起软键盘的focus()方法必须放在用户主动触发的点击事件回调中执行,放在异步回调里会被大多数移动端浏览器拦截,无法生效
  • 如果输入框弹出后遮挡了游戏区域,可以监听输入框的focus事件,手动调整页面滚动位置或者游戏区域的高度,避免内容被软键盘遮挡

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:45:03