如何将 Ionic 输入类型文件设置为 Button

How to style Ionic input type file as a Button

我想设计离子文件选择器按钮的样式。

<input type="file" id="myFileInput">

但是 Ionic 没有输入类型文件按钮。 那么我怎样才能获得比带有 Choose a File 文本的标准 Button 更好看的按钮呢?

如果您只想将 <input> 元素设置为按钮样式,例如,您可以采用此 post 的建议样式之一:http://geniuscarrier.com/how-to-style-a-html-file-upload-button-in-pure-css/

或来自 CSS-tricks 的另一个示例:https://css-tricks.com/snippets/css/custom-file-input-styling-webkitblink/

或这个:http://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/

请记住,在移动设备上它可能无法工作,您可能需要一个 cordova 插件。例如:https://github.com/apache/cordova-plugin-file

我发现最好的方法是使用带有 for 属性的标签并使用 css 对其进行自定义。请记住,for 标签必须是输入 id。因此,当用户点击标签时,将触发输入。

<label class="myFakeUploadButton" for="myFileInput">Upload</label>
<input type="file" id="myFileInput">
#myFileInput{
  position: absolute;
  opacity: 0;
}

.myFakeUploadButton{
 /* Whatever you want */
}

如果您愿意,可以使用这样的图标:

<input type="file" accept="image/*" capture="camera" (change)="onFileSelected($event)" id="fileInput"/>
<label for="fileInput" icon-only ion-button>
    <ion-icon name="camera"></ion-icon>
</label>

这种解决方案怎么样(对我有用):

 <ion-button (click)="f.click">Upload</ion-button
.inputFile {
   width: 0;
   height: 0;
 }

& 根据你的喜好设计你的按钮,如果你点击 ion-button 你实际上会点击 input file

Zerzeri 的回答很好但不完整这是我对上述内容的实现

         <ion-item>
            <ion-button expand="full" (click)="f.click()">
              <ion-icon lazy="true" slot="start" name="image"></ion-icon>
              <ion-label slot="end">Profile pic</ion-label>
            </ion-button>
              <input class="ion-hide" #f type="file" (change)="loadImageFromDevice($event)" id="file-input"
                accept="image/png, image/jpeg">

         </ion-item>

在你的TS中:

handleFileInput(event) {
    console.log(event);
    this.userDetails.profilePic = event.target.files[0];
  }