使用JavaScript查找图像的高度-图像加载错误
Finding height of image using JavaScript - image load error
我似乎无法在Typo3网站上使用Javascript找到图像的高度。
基本上我有javascript运行在一个$(document).ready(function () {
。它在页面上查找图像并查找其高度&,然后根据结果执行操作。
有时有效,有时无效。通常,我得到一个宽度值,但没有高度值。我怀疑这是因为浏览器还没有完成图片的加载。
为了解决这个问题,我包含了一个2秒的延迟,以确保img在寻找其高度之前被加载。但这并不是一个很好的解决问题的方法,尤其是当有人下载速度较慢的时候。
在执行操作之前,我如何检查图像是否已完全加载?
下面是一些HTML:
<div class="resize-thumb-img">
<img src="#.jpg" />
</div>
<div class="resize-thumb-img">
<img src="#.jpg" />
</div>
<div class="resize-thumb-img">
<img src="#.jpg" />
</div>
和一些JS:
$(document).ready(function () {
setTimeout(myFunctionX, 2000);
function myFunctionX() {
$(".resize-thumb-img img").each(function(){ //for each image
console.log("working on image: "+$(this).width() +"x"+$(this).height());
/* MORE WORK HERE */
});
}
});
控制台日志可以给出235x420
或235x0
或0x0
等结果
我找到了一个解决方案,我认为在这种情况下有帮助。它检查图像的宽度是否为"0"。如果是,它等待1秒,然后再次尝试。如果不是0,它就调用之前的函数。在第一个if语句中包含|| null
可能会有用-我没有在所有浏览器上测试过。
$(document).ready(function () {
checkLoadState();
function checkLoadState() //checks to see if images are loaded before continuing
{
if ($(".resize-thumb-img img").width() != "0")
{
console.log("Images loaded. Resizig...");
myFunctionX();
}
else
{
console.log("Waiting for images to load.");
setTimeout(checkLoadState, 1000); // check again in a second
}
}
function myFunctionX() {
$(".resize-thumb-img img").each(function(){ //for each image
console.log("working on image: "+$(this).width() +"x"+$(this).height());
/* MORE WORK HERE */
});
}
});
你可以试试下面这个:
$('img').each(function() {
$(this).attr('height',$(this).height());
$(this).attr('width',$(this).width());
});
这将帮助您使用jquery找到图像的高度
如果您可以控制服务器端脚本,难道您不能简单地将位图的大小与其文件名一起存储在数据库中吗?然后可以设置IMG元素的WIDTH和HEIGHT属性。
你需要做的是为任何尚未加载的图像绑定一个函数到load事件,就像这样
function processImage(imageElement){
// do your stuff here
var img=$(imageElement);
console.log("working on image: "+img.width() +"x"+img.height());
}
$(document).ready(function () {
// iterate through the images
$(".resize-thumb-img img").each(function(){
var img = $(this);
if(img.width()==0 || img.height()==0){
// image has not fully loaded yet, so process it once loaded
img.on('load',function(){processImage(this);})
}else{
// image is loaded so process the image straight away
processImage(this);
}
})
})
相关文章:
- 在通过child.print()打印之前,我如何等待图像加载到我的新窗口中
- 在检索数据时是否可以停止图像加载请求
- 如何让我的网站上的WEBP图像加载在morzilla firefox中有一个可能的解决方案吗?如果是,那么如何
- jQuery:获取图像加载错误的详细信息
- 在safari和chrome中,js图像加载产生了奇怪的结果
- 图像加载不适用于 IE 8 或更低版本
- 这个图像加载功能有什么作用
- JavaScript 图像加载器不起作用
- 动态图像加载是否会减少服务器过载
- 跨来源图像加载被拒绝-仅限iPhone-简单图像上传
- 纯javascript的进度图像加载程序仅当用户单击提交html表单时
- 使用JavaScript延迟图像加载
- 如果当前图像加载缓慢,如何加载其他图像
- HTML图像加载触发一个错误
- 将图像加载到localStorage,并将图像src设置到该位置
- jquery图像加载检查错误
- 将图像加载到织物画布背景中
- 需要在bootstrap css中单击时将图像加载为模态
- 正在显示加载..在将新图像加载到网站时播放动画
- 砖石事件:在图像加载和布局完成后调用事件