关于文件上传

使用伪元素给文件上传控件改变样式

IE10+浏览器使用的是::-ms-browse伪元素,可以改变按钮模样部分的边框、背景色、高度等,Chrome下使用的伪元素为::-webkit-file-upload-button。
html body

<form>
  <p class="file">
    <label for="file-input">Upload your image</label>
    <input id="file-input" type="file" name="file-input" />
  </p>
</form>

css样式

input[type="file"]::-webkit-file-upload-button {
  background: #E62163;
  border: none;
  padding: .5em 1em;
  color: #fff;
  border-radius: .2em;
}
input[type="file"]::-ms-browse {
  background: #E62163;
  border: none;
  padding: .5em 1em;
  color: #fff;
  border-radius: .2em;
}

不使用伪元素给文件上传控件改变样式

html body

<form>
  <p class="file">
    <input id="file-input" type="file" name="file-input" />
    <label for="file-input">Upload your image</label>
  </p>
</form>

css样式

.file {
  position: relative;
}
.file input {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
.file label {
  background: #39D2B4;
  padding: 5px 20px;
  color: #fff;
  font-weight: bold;
  font-size: .9em;
  transition: all .4s;
}
.file input[type="file"]:hover + label,
.file input[type="file"]:focus + label {
  background: #34495E;
  color: #39D2B4;
}

实时显示上传图片

这里其实是用到了FileReader对象,FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 File 或 Blob 对象指定要读取的文件或数据。
js代码:

<script>
  var inputBox = document.getElementById('file-input');
  var img = document.getElementById('img');
  inputBox.addEventListener('change', function() {
    var reader = new FileReader();//异步读取文件内容
    reader.readAsDataURL(inputBox.files[0]);//开始读取指定的Blob中的内容。一旦完成,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容。
    reader.onload = function() {  //处理load事件,该事件在读取操作完成时触发。
      img.src = this.result;//文件的内容。该属性仅在读取操作完成后才有效,数据的格式取决于使用哪个方法来启动读取操作。
    }
  })
</script>
posted @ 2019-01-15 15:37  暮雪&&如霜  阅读(154)  评论(0编辑  收藏  举报