Jquery 为什么';这难道不能得到一个图像';什么是原生维度?
我正在处理一个lightbox,我需要获得要显示的图像元素的本机维度。我正在研究一种基于CSS技巧的方法。我的图片本机为400x400像素,但我的方法始终返回0x0。以下是相关代码:Jquery 为什么';这难道不能得到一个图像';什么是原生维度?,jquery,html,image,src,Jquery,Html,Image,Src,我正在处理一个lightbox,我需要获得要显示的图像元素的本机维度。我正在研究一种基于CSS技巧的方法。我的图片本机为400x400像素,但我的方法始终返回0x0。以下是相关代码: function setLuxboxSize () { console.log("picture original: " + luxpic.attr('src')); var testingImage = new Image(); testingImage.src = luxpi
function setLuxboxSize () {
console.log("picture original: " + luxpic.attr('src'));
var testingImage = new Image();
testingImage.src = luxpic.attr('src');
//console.log('testingImage src:' + testingImage.attr('src'));
var picWidth = testingImage.width;
var picHeight = testingImage.height;
console.log("original width: " + picWidth);
console.log("original height: " + picHeight);
};
另外,当注释掉的console.log行处于活动状态时,我在控制台中得到以下错误:uncaughttypeerror:Object#没有方法“attr”。第一行console.log按预期返回一个src。我做错了什么
编辑:问题是图像尚未加载,在加载之前,宽度和高度调用不会返回正确的值。检查LorDex或Satpal的答案,以使用onload功能获取尺寸。您必须先加载图像,然后才能检查其尺寸
var testingImage = new Image();
testingImage.src = luxpic.attr('src');
testingImage.onload = function () {
var picWidth = this.width;
var picHeight = this.height;
console.log("original width: " + picWidth);
console.log("original height: " + picHeight);
};
您可以在加载后检查实际图像大小。为此,请使用.onload()方法:
什么是
luxpic
var?您的代码希望它是包装好的jQuery结果,如var luxpic=$(“#image”)代码>哦,是的,这些东西是在其他地方定义的,不过我并没有把这部分写出来:)
testingImage.onLoad(function() {
var picWidth = testingImage.width;
var picHeight = testingImage.height;
console.log("original width: " + picWidth);
console.log("original height: " + picHeight);
});