Home > Web Front-end > H5 Tutorial > body text

Share an image and text example of H5 uploading local images and previewing functions

零下一度
Release: 2017-05-09 10:59:52
Original
2763 people have browsed it

This article mainly introduces the implementation code of H5uploadthis map film and preview in detail. It has certain reference value. Interested friends can refer to it.

Recently, I need the function of H5 to upload and display pictures , as shown in the picture:

Directly upload the code:

html part

<p class="works-wrap"> 
 <p class="figure-box" id="figure_box"></p> 
 <p class="add-btn"> 
  <input type="file" id="imgUploadBtn" /> 
  <a href="javascript:void(0);" rel="external nofollow" ><i></i>添加作品</a></p> 
 </p> 
</p>
Copy after login

I used css to set input[type=file] to optical:0; so that it looks more like a native upload.

var addWork = { 
 add: function(btn, figure_box) { 
 var figureBox = document.getElementById(figure_box); //获取显示图片的p元素 
 var input = document.getElementById(btn); //获取选择图片的input元素 
 //这边是判断本浏览器是否支持这个API。 
 if (typeof FileReader === &#39;undefined&#39;) { 
  alert("浏览器版本过低,请先更新您的浏览器~"); 
  input.setAttribute(&#39;disabled&#39;, &#39;disabled&#39;); 
 } else { 
  input.addEventListener(&#39;change&#39;, readFile, false); 

 //如果支持就监听改变事件,一旦改变了就运行readFile函数。 
 } 
 
 function readFile() { 
  var file = this.files[0]; //获取file对象 
  //判断file的类型是不是图片类型。 
  if (!/image\/\w+/.test(file.type)) { 
  alert("请上传一张图片~"); 
  return false; 
  } 
 
  var reader = new FileReader(); //声明一个FileReader实例 
  reader.readAsDataURL(file); //调用readAsDataURL方法来读取选中的图像文件 
  //最后在onload事件中,获取到成功读取的文件内容,并以插入一个img节点的方式显示选中的图片 
  reader.onload = function(e) { 
  // 创建一个新增的图片和文字input 
  var figure = $(&#39;<p class="figure"><p class="figure-hd">我的头部</p><p class="figure-bd"><img src="&#39; + this.result + &#39;" /><textarea placeholder="请输入文字"></textarea></p></p>&#39;); 
  figure.appendTo(figureBox); 
  } 
 } 
 } 
}
Copy after login

【Related recommendations】

1. Free h5 online video tutorial

2. HTML5 full version manual

3. php.cn original html5 video tutorial

The above is the detailed content of Share an image and text example of H5 uploading local images and previewing functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template