<input> 的 capture 属性 ——它主要用于 移动端(手机/平板),和 文件上传 配合使用 通过设置type=“file“和accept属性,配合capture的不同值(如“user“调

1. 基本语法

<input type="file" accept="image/*" capture>

  • type="file":文件上传。

  • accept="image/*":限制只能选择图片。

  • capture:告诉浏览器 直接调用设备摄像头 / 麦克风 来采集内容,而不是从相册里挑。


2. capture 的可选值

属性值作用
capture(无值)启用默认设备(通常是后置摄像头)
capture="user"启用前置摄像头(自拍)
capture="environment"启用后置摄像头
capture="microphone"调用麦克风采集音频(需配合 accept="audio/*"

3. 常见用法示例

① 调用后置摄像头拍照

<input type="file" accept="image/*" capture="environment">

② 调用前置摄像头自拍

<input type="file" accept="image/*" capture="user">

③ 调用摄像头拍摄视频

<input type="file" accept="video/*" capture>

④ 调用麦克风录音

<input type="file" accept="audio/*" capture="microphone">


4. 注意事项

  1. PC 浏览器大部分不支持,主要针对 移动端浏览器(Safari, Chrome, 微信内置浏览器)

  2. capture 只是 建议,最终是否调用摄像头/麦克风由 浏览器决定

  3. 如果没设置 accept,用户可能依然能选择文件,而不是强制调用摄像头。

  4. 在 iOS Safari 上,captureaccept="image/*" 搭配才能生效。

  5. 如果要上传后端,需要用 FormData 读取文件并提交。


5. 简单上传 + 预览 Demo

<input type="file" accept="image/*" capture="environment" id="cameraInput">
<br>
<img id="preview" width="200">

<script>
  const input = document.getElementById("cameraInput");
  const preview = document.getElementById("preview");

  input.addEventListener("change", (event) => {
    const file = event.target.files[0];
    if (file) {
      preview.src = URL.createObjectURL(file);
    }
  });
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星空下的DeppBing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值