Home > Article > Web Front-end > Share an image and text example of H5 uploading local images and previewing functions
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>
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 === 'undefined') { alert("浏览器版本过低,请先更新您的浏览器~"); input.setAttribute('disabled', 'disabled'); } else { input.addEventListener('change', 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 = $('<p class="figure"><p class="figure-hd">我的头部</p><p class="figure-bd"><img src="' + this.result + '" /><textarea placeholder="请输入文字"></textarea></p></p>'); figure.appendTo(figureBox); } } } }
【Related recommendations】
1. Free h5 online video tutorial
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!