[英]How to get the dimensions of an image after it has been loaded?
I'm trying to make my image more reliable / responsive in a modal. 我正在尝试使我的图像在模态中更可靠/响应更快。
and I'm pulling the image source from my database (MySQL) and show the image on a modal. 然后从数据库(MySQL)中提取图像源,并以模式显示图像。
I have this code: 我有以下代码:
<a class='modal-trigger' href='#view-image' onclick='getImage(`<?php image source; ?>`)'></a>
After that this is my JavaScript 之后,这就是我的JavaScript
function getImage(imgsrc){
$("#item-thumb").attr("src",imgsrc);
var height = $('#item-thumb').height();
if(height > '600'){
console.log(height);
}else{
console.log(height);
}
}
My problem is when I'm getting the height of the image it always outputs 0. I think the script itself is getting only the blank image, I suppose? 我的问题是,当我得到图像的高度时,它始终输出0。我想脚本本身仅获得空白图像,我想吗? Is there any other way to get the dimension of an image using jQuery?
还有其他方法可以使用jQuery获取图像的尺寸吗?
First of all you have to pass string to javascript using single quotes '
, you are passing with back ticks. 首先,您必须使用单引号
'
将字符串传递给javascript,然后传递带有反勾号的字符串。
corect corect
<a class='modal-trigger' href='#view-image' onclick='getImage(`<?php image source; ?>`)'></a>
To: 至:
<a class='modal-trigger' href='#view-image' onclick="getImage('<?php image source;?>')"></a>
Also, what is the purpose of href='#view-image'
. 另外,
href='#view-image'
的目的是什么。
Are you changing the hash on click of link or calling onclick
event? 您是在单击链接时更改哈希还是调用
onclick
事件?
If u need to get the image height then u need to render the image on dom (document) unless , u can't get the image height 如果您需要获取图像高度,则需要在dom(文档)上渲染图像,除非,您无法获取图像高度
If u have image data on database, then do the height operation using PHP
如果您在数据库上有图像数据,则使用
PHP
进行高度操作
list($width, $height, $type, $attr) = getimagesize("image_name.jpg");
You need to wait for the image to load before getting its height. 您需要等待图像加载后才能获取其高度。 Try using this code:
尝试使用以下代码:
$('#item-thumb').load(function () {
console.log($(this).height());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.