我想创建一个div附加拖放功能,当有人点击它,他们可以选择他们的形象.
我已经编码了一些东西,它的可以
– 点击div并选择您的图像
– 上传前预览您的图像
你可以检查我的小提琴
CSS
- .uploader {width:300px;height:350px;background:#f3f3f3;border:2px dashed #e8e8e8;}
JavaScript的
- var imageLoader = document.getElementById('filePhoto');
- imageLoader.addEventListener('change',handleImage,false);
- function handleImage(e) {
- var reader = new FileReader();
- reader.onload = function (event) {
- $('.uploader').html( '<img width="300px" height="350px" src="'+event.target.result+'"/>' );
- }
- reader.readAsDataURL(e.target.files[0]);
- }
HTML
- <div class="uploader" onclick="$('#filePhoto').click()">click here or drag here your images for preview and set userprofile_picture data</div>
- <input type="file" name="userprofile_picture" id="filePhoto" style="display:block;width:185px;" />
解决方法
你可以用很少的CSS技巧来做到这一点.
输入元素接受下降.
我改变了你的代码如下:
输入元素接受下降.
我改变了你的代码如下:
CSS
- .uploader {
- position:relative;
- overflow:hidden;
- width:300px;
- height:350px;
- background:#f3f3f3;
- border:2px dashed #e8e8e8;
- }
- #filePhoto{
- position:absolute;
- width:300px;
- height:400px;
- top:-50px;
- left:0;
- z-index:2;
- opacity:0;
- cursor:pointer;
- }
- .uploader img{
- position:absolute;
- width:302px;
- height:352px;
- top:-1px;
- left:-1px;
- z-index:1;
- border:none;
- }
JavaScript的
- var imageLoader = document.getElementById('filePhoto');
- imageLoader.addEventListener('change',false);
- function handleImage(e) {
- var reader = new FileReader();
- reader.onload = function (event) {
- $('.uploader img').attr('src',event.target.result);
- }
- reader.readAsDataURL(e.target.files[0]);
- }
HTML
- <div class="uploader" onclick="$('#filePhoto').click()">
- click here or drag here your images for preview and set userprofile_picture data
- <img src=""/>
- <input type="file" name="userprofile_picture" id="filePhoto" />
- </div>
我希望它有帮助.您可以查看http://jsfiddle.net/ELcf6/4/和其他版本http://jsfiddle.net/ELcf6/8/