【问题标题】:Display image when preview button is click before upload in jQuery [duplicate]在jQuery中上传之前单击预览按钮时显示图像[重复]
【发布时间】:2017-05-12 09:36:07
【问题描述】:

我有一个这样的 HTML 表单:

     <form id="myForm" name="myform" action="register/index.php" method="post" enctype="multipart/form-data" >

<input class="myfile" id="banner" name="banner" type="file" accept="image/png, image/gif, image/jpeg" >

<a href="#" onclick="getPreview();>Preview</a>

 <input type="submit"  value="submit" name="submit">

</form>

我想要做的是当用户点击预览按钮时,他选择的文件将显示在&lt;div id="myid"&gt;&lt;/div&gt;的某处

<script>

function getPreview(){

// what should write here to make this working
}

</script>

任何人都请帮忙,如何使用 jQuery 或 JavaScript 做到这一点?

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

试试这个,可能会有所帮助,否则您可以根据自己的要求定制更多

function readURL(input) {  
   $('.preview').show();
  $('#blah').hide();
  $('.preview').after('<img id="blah" src="#" alt="your image" style="display:none;"/>');
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
      $('#blah')
      .attr('src', e.target.result)
      .width(150)
      .height(200);
    };
    reader.readAsDataURL(input.files[0]);
  }
}

function getPreview(){
  $('.preview').hide();
  $('#blah').show();
}
<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
   <div>
      <input type='file' onchange="readURL(this);" />
   </div>
  <div>
  <a href="#" class="preview" onclick="getPreview();">Preview</a><br/>   
    </div>
</body>
</html>

【讨论】:

  • 我怎样才能动态创建 img 标签然后在其中显示这个图像,就像我有我的 div 有一些文本,我想删除该文本并放置这个图像。
  • 您要求我在点击链接显示图片后删除预览文本?
  • 是的,并且当新图像被选择时,旧图像应该消失 span>
  • 现在再试一次我的代码,我已经按照你的要求更改了代码。
  • 非常感谢,现在可以按照我的意愿工作了。
猜你喜欢
  • 2018-08-12
  • 2013-11-06
  • 1970-01-01
  • 1970-01-01
  • 2018-03-30
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
相关资源
最近更新 更多