如何使用按钮样式在 Ionic 2+ 中创建自定义文件输入? [英] How to create a custom file input in Ionic 2+ with a button styling?

查看:16
本文介绍了如何使用按钮样式在 Ionic 2+ 中创建自定义文件输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的模板:

<label>{{label}}</label>
<input type="file" (change)="fileUpload($event)" id="file-input" style="position:absolute; top: -999999px" #fileInp>
<button ion-button (click)="onClick()">Upload</button>

和 ts 文件:

@ViewChild('fileInp') fileInput: ElementRef;
@Input() label: string;
@Output() data = new EventEmitter<FormData>();

fileUpload(event) {
  let fd = new FormData();
  fd.append('file', event.srcElement.files[0]);
  this.data.emit(fd);
}

onClick() {
  this.fileInput.nativeElement.click();
}

在 Android 和浏览器上一切正常,但在 iOS 上则不行.如果我禁用模板中的按钮,同样的代码也能工作.

Everything works fine on Android and in the browser, but not on iOS. The same code works if I disable the button in the template.

推荐答案

您无法在 iOS 上触发对文件输入的点击.一种解决方法是使用 css 将输入元素的不透明度设置为 0,并将其放置在按钮的顶部.这样,文件输入不会被看到,但会在点击按钮时被点击.

You can't trigger the click on a file input on iOS. A workaround is to use css to set the opacity of the input element to 0, and place it just on top of the button. That way, the file input won't be seen, but it will be clicked when clicking the button.

<ion-item>
  <label>{{label}}</label>
  <input type="file" (change)="fileUpload($event)" id="file-input" style="opacity: 0" #fileInp>
  <button ion-button (click)="onClick()">Upload</button>
</ion-item>

然后在 .scss 文件中:

and then in the .scss file:

#file-input {
  opacity: 0;
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  left: 0;
  z-index: 999;
}

可能还有其他一些方法可以解决这个问题,但我在过去开发的应用上就是这样管理的.

There're probably some other ways to fix this issue, but that's how I managed on an app I worked on in the past.

这篇关于如何使用按钮样式在 Ionic 2+ 中创建自定义文件输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆