一个分享WordPress、Zblog、Emlog、Typecho等主流博客的教程网站!
当前位置:网站首页 > 编程知识 > 正文

微信小程序实现一个用于文本输入的弹出框

作者:xlnxin发布时间:2026-07-28分类:编程知识浏览:98


导读:方式一:使用微信自带API(简单快捷)如果你的需求比较简单,可以直接使用微信官方提供的 wx.showModal 接口。只需将 editable&n...

方式一:使用微信自带 API(简单快捷)

如果你的需求比较简单,可以直接使用微信官方提供的 wx.showModal 接口。只需将 editable 属性设置为 true

Page({
  showInputDialog() {
    wx.showModal({
      title: '提示',
      content: '这是一个带输入框的弹窗',
      editable: true, // 开启输入框功能
      placeholderText: '请输入内容...', // 设置输入框提示语
      success: (res) => {
        if (res.confirm) {
          console.log('用户点击了确定,输入的内容为:', res.content);
        } else if (res.cancel) {
          console.log('用户点击了取消');
        }
      }
    });
  }
})

方式二:自定义弹窗组件(高度自定义)

如果你需要自定义弹窗的样式、布局,或者需要更复杂的交互逻辑,可以通过组合 view、input 等基础组件来手动实现。

1. WXML 结构:
使用一个固定定位的遮罩层(.toastbg)覆盖全屏,并在其上放置一个包含标题、输入框和按钮的弹窗容器(.showToast)。通过一个布尔值(如 isShow

<!-- 弹窗容器 -->
<view class="toast-box" hidden="{{!isShow}}">
  <!-- 半透明遮罩层 -->
  <view class="toastbg" bindtap="cancel"></view>
  <!-- 弹窗主体 -->
  <view class="showToast">
    <view class="toast-title">修改信息</view>
    <view class="toast-main">
      <input 
        class="toast-input" 
        placeholder="请输入内容" 
        bindinput="onInput" 
        value="{{inputValue}}"
      />
    </view>
    <view class="toast-button">
      <button class="btn-cancel" bindtap="cancel">取消</button>
      <button class="btn-confirm" bindtap="confirm">确定</button>
    </view>
  </view>
</view>

2. WXSS 样式(核心部分):
遮罩层需要使用 position: fixed 覆盖整个屏幕,并设置半透明背景色;弹窗主体可以使用绝对定位居中。

.toast-box {
  position: fixed;
  top: 0; left: 0;
  width: 100%; height: 100%;
  z-index: 999;
}
.toastbg {
  position: absolute;
  width: 100%; min-height: 100vh;
  background-color: black;
  opacity: 0.5; /* 半透明遮罩 */
}
.showToast {
  position: absolute;
  width: 70%; left: 15%; top: 40%;
  background-color: #fff;
  border-radius: 16rpx;
  text-align: center;
}
.toast-input {
  margin: 20rpx 5%;
  border: 1px solid #ddd;
  padding: 10rpx 20rpx;
}

3. JS 逻辑:
在页面的 data 中定义 isShow: false 和 inputValue: ''。通过事件处理函数来控制弹窗的显隐,并在 onInput 函数中实时获取用户输入的文本,在 confirm 函数中进行最终的数据处理。

标签:程序小程序js