上载图像文件后不显示Div背景预览

时间:2018-07-31 13:18:56

标签: javascript jquery image-uploading

我正在使用基本的html输入文件上传器上传图像文件,并使用div'editor-image-1'作为上传图像的预览。我正在尝试使用以下代码来处理此图像,但div不会更改其背景。控制台日志“成功”正在触发,但未显示图像:

$("#editor-upload-1").change(function() {
  $('#editor-image-1').css('background', "#FFF");
  var file = this.files[0];
  var imagefile = file.type;
  var valid = ["image/jpeg","image/png","image/jpg"];
  if(!((imagefile==valid[0]) || (imagefile==valid[1]) || (imagefile==valid[2]))) {
    $('#editor-image-1').css('background', "#F00");
    alert("Wrong image format");
    return false;
  } else {
    var reader = new FileReader();
    reader.onload = imageIsLoaded;
    reader.readAsDataURL(this.files[0]);
  }
});


function imageIsLoaded(e) {
  console.log("success");
  $('#editor-image-1').css('background', 'url("' + e.target.result + '")');
};

1 个答案:

答案 0 :(得分:-1)

这很好 可能会有很多失败 请参考下面的代码

    <!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>functionality</title>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  </head>
<body>
 <style>
     .wrapper {
  width: 100%;
  /* whatever width you want */
  display: inline-block;
  position: relative;
  background-size: contain;
  margin: 0 auto;
}
.wrapper:after {
  padding-top: 75%;
  /* this llama image is 800x600 so set the padding top % to match 600/800 = .75 */
  display: block;
  content: '';
}
.main {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  color: black;
  text-align: center;
  margin-top: 5%;
}
 </style> 
<input type="file" id="editor-upload-1">
<div class="wrapper">
        <div class="main" id="main">

        </div>
      </div>
<script>
    $(function(){
        $("#editor-upload-1").change(function() {
        $('#main').css('background', "#FFF");
        var file = this.files[0];
        var imagefile = file.type;
        var valid = ["image/jpeg","image/png","image/jpg"];
        if(!((imagefile==valid[0]) || (imagefile==valid[1]) || (imagefile==valid[2]))) {
            $('#main').css('background', "#F00");
            alert("Wrong image format");
            return false;
        } else {
            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(this.files[0]);
        }
        });



    });

      function imageIsLoaded(e) {
      console.log("success");
       $('#main').css('background', 'url("' + e.target.result + '")');
       $('#main').css('top center no-repeat;');

      };
    </script>
</body>
</html>