我正在使用JCrop jquery库,我在使用HTML文件控件上传文件后提供图像预览。
查看部分(演示数据)
<input type="file" id="photograph" />
<img src="#" id="target" />
Javascript代码
// for setting img src
function readURL(input) {
console.log("readURL");
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#target').attr('src', e.target.result);
console.log("inside if =>"+e.target.result);
}
console.log("outside IF");
reader.readAsDataURL(input.files[0]);
}
}
// for setting pre-selected cropping area
function setProperties(){
console.log("set properties");
$('#target').Jcrop({
setSelect: [0,12,23,43]
});
}
// on change event for fileupload
$("#photograph").change(function(){
console.log("change event called!");
readURL(this);
setProperties();
});
输出
change event called!
readURL
outside IF
set properties
inside if=>data:image/jpeg;base64,/9j/4gIcSUNDX1BST0ZJTEUAAQEAAAIMbGNtcwIQAABtbnRyUkdC…sXK2t+4UdmuSVl64hb2gMHh1Nhm83DAdQJniIM6eZUxzuYCR2my3FSwGpVbzBdwlgrrc/
我想在上传图片文件后设置一些属性,但是&#34;在if =&gt;&#34;内[见上面发布的输出]在最后被调用。那为什么会这样呢?我应该如何解决这个问题?
答案 0 :(得分:1)
您需要在设置图片setProperties
后调用source
并将图片loaded
function readURL(input) {
console.log("readURL");
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#target').attr('src', e.target.result);
console.log("inside if =>"+e.target.result);
// Call after source setted and image file loaded
setProperties();
}
console.log("outside IF");
reader.readAsDataURL(input.files[0]);
}
}