![](/img/trans.png)
[英]how to make sure that a popup window is fully loaded when using postMessage API?
[英]How to make sure that an image is fully loaded in the DOM
我正在將裁剪工具集成到我的應用程序中。 (傑克羅普)
我將以下JavaScript集成到頁面中:
$(function() {
$("#imgInp").change(function(){
readURL(this);
});
});
function update_crop(coords) {
var rx = 100/coords.w;
var ry = 100/coords.h;
$('#preview').css({
width: Math.round(rx * 760) + 'px',
height: Math.round(ry * 1000) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#cropbox').attr('src', e.target.result);
$('#preview').attr('src', e.target.result);
$('#cropbox').Jcrop({
onChange: update_crop,
onSelect: update_crop,
setSelect: [0, 0, 500, 500],
aspectRatio: 10 / 13.15
});
}
reader.readAsDataURL(input.files[0]);
}
}
在我的HTML中,我有以下內容:
<h1>Image to load</h1>
<form id="form1" runat="server">
<input type='file' id="imgInp" />
</form>
<img id="cropbox" src="#" alt="your image">
<h4>Preview:</h4>
<div style="width:100px; height:100px; overflow:hidden">
<img id="preview" src="#" alt="your image">
</div>
因此,基本上,我為用戶提供了上傳圖片的可能性,然后讓他可視化要裁剪的區域。
問題是,當我加載第一個圖片時,它很好,但是當我第二次加載另一個圖時,它在img#cropbox
元素中沒有更改。
因此,基本上$('#cropbox').Jcrop
事件在瀏覽器更改$("#cropbox").attr('src',e.target.result)
我如何確保僅在執行$("#cropbox").attr('src',e.target.result)
並且圖像已完全加載$('#cropbox').Jcrop
執行$('#cropbox').Jcrop
?
圖像元素也有加載事件。 在設置src
屬性之前,請將該函數包裝在該映像的加載事件回調中。
$('#cropbox').load(function(){
$('#cropbox').Jcrop({
onChange: update_crop,
onSelect: update_crop,
setSelect: [0, 0, 500, 500],
aspectRatio: 10 / 13.15
});
});
$('#cropbox').attr('src', e.target.result);
嘗試設置間隔輪詢以查看新的圖像源是否與預期的源匹配。
在繼續進行JCrop之前,新的圖像源(實際)應與預期的圖像源(您設置的圖像源)匹配。
這是一個簡化的示例:
function checkImageLoaded(newImg){
if (newImg == expectedImg){
$('#cropbox').Jcrop({
onChange: update_crop,
onSelect: update_crop,
setSelect: [0, 0, 500, 500],
aspectRatio: 10 / 13.15
});
//clear the interval
window.clearInterval(imageInterval);
}
}
function pollImageSource() {
//get the new Image source
//set the expect Image source
//then check if they match
var imageInterval = setInterval(function(){ checkImageLoaded(newImageSource); }, 300);
}
有很多圖像插件可以檢測是否加載了圖像,但是我認為這不是必需的。
而且,David Walsh具有更強大的輪詢機制。
https://davidwalsh.name/javascript-polling
摘抄:
// Usage: ensure element is visible
poll(function() {
return document.getElementById('lightbox').offsetWidth > 0;
}, 2000, 150);
但這可能不起作用,因為您的圖像已經加載。 您將不得不對該腳本進行大量修改以比較上述圖像源。
我認為您應該使用圖片的onload事件。 當瀏覽器完成渲染圖像后,就會觸發該圖像,並且每次圖像更改時都會重新開始。
簡單點
您可以使用jQuery實現相同的功能:$(“ img”)。on(“ load”,function(){....});
(有一個差不多的事情,有一個更早的答案,對不起)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.