点击img占位符上传图片而不是占位符
问题描述:
请注意,我知道下面的代码远非诗歌,我是初学者。考虑到这一点,我具有以下一个<form>
内部HTML:点击img占位符上传图片而不是占位符
<div class="image-upload">
<img id="send_photo_img1" src="assets/images/index2.png"/>
<input id="send_photo_input1" type="file"/>
<img id="send_photo_img2" src="assets/images/index2.png"/>
<input id="send_photo_input2" type="file"/>
</div>
目标:一旦用户点击图像(index2.png,这与“+”号的占位符),窗打开像从输入=文件,用户选择img并且它被加载而不是占位符。 (基于@Ivan Bayev的answer here,而他的代码,这等好事,矿山变得十分笨拙ATM ..)
jQuery的
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#send_photo_img1').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#send_photo_img1").click(function(){
$("#send_photo_input1").trigger("click");
$("#send_photo_input1").change(function(){
readURL(this);
});
});
CSS
.image-upload > input
{
display: none;
}
:
休息的代码
它的工作原理。但是:(1)我觉得jQuery非常糟糕,(2)最大的担忧 - 一旦显示图像而不是占位符,我仍然有30-40秒的“加载”符号。然后它消失了。
任何建议是高度appreaciated。谢谢!
答
以防万一任何人对上述解决方案感兴趣,在这里。
首先,上面的代码附加到ID,如果输入=文件的许多实例位于单个页面上,则这是很糟糕的。所以首先将它重新附加到类上。每一块看起来像:
<div class="img_upload">
<img class="send_photo_img" src="assets/images/index2.png"/>
<input class="send_photo_input" type="file"/>
</div>
然后它需要一些变通方法来选择通过jQuery:
$(".img_upload img").click(function(){
var imgDiv = $(this).next(".send_photo_input");
imgDiv.trigger("click");
imgDiv.change(function(){
//console.log('Display that to trace results');
//your function here.
});
});
CSS:
.img_upload input
{
display: none; // hide original input
}
.img_upload img
{
width: 90px;
height: 90px;
cursor: pointer;
}
在我的问题的ReadURL功能的实际工作完善,只是改变这一点:
reader.onload = function (e) {
$('#send_photo_img1').attr('src', e.target.result);
}
这样:
reader.onload = function (e) {
$(input).prev(".send_photo_img").attr('src', e.target.result);
}
而且请注意,我用prev(),而你可以使用更普遍的:
$(input).parent().find(".send_photo_img").attr('src', e.target.result);
注意,你可以用它代替的img更好的效果的图标。
这个答案只是让你知道上述问题的工作代码。如有需要,请随时咨询其他细节。