[英]Can't get img width and height jQuery
I'm totaly confused with this piece of code. 我对这段代码完全感到困惑。 When I just load the page imgWidth1 and imgHeight1 are both equal to "0" But when I resize my window, the code works and imgWidth1 and imgHeight1 have the same value as the image dimension.
当我仅加载页面时, imgWidth1和imgHeight1都等于“ 0”,但是当我调整窗口大小时,代码有效,并且imgWidth1和imgHeight1与图像尺寸具有相同的值。
All help is welcome, thanks. 欢迎所有帮助,谢谢。
var imgWidth1 = $("#image-hover-0").outerWidth();
var imgHeight1 = $("#image-hover-0").outerHeight();
$("#hover-img-0").css("width", imgWidth1 + "px");
$("#hover-img-0").css("height", imgHeight1 + "px");
$("#hover-img-0").css("line-height", imgHeight1 + "px");
$(window).resize(function() {
var imgWidth = $("#image-hover-0").outerWidth();
var imgHeight = $("#image-hover-0").outerHeight();
$("#hover-img-0").css("width", imgWidth + "px");
$("#hover-img-0").css("height", imgHeight + "px");
$("#hover-img-0").css("line-height", imgHeight + "px");
});
This is most likely due to the fact that your code is not nested inside a $(window).load()
function call. 这很可能是由于您的代码未嵌套在
$(window).load()
函数调用中。 Modify your code to the following: 将您的代码修改为以下内容:
$(window).load(function(){
var imgWidth1 = $("#image-hover-0").outerWidth();
var imgHeight1 = $("#image-hover-0").outerHeight();
$("#hover-img-0").css("width", imgWidth1 + "px");
$("#hover-img-0").css("height", imgHeight1 + "px");
$("#hover-img-0").css("line-height", imgHeight1 + "px");
$(window).resize(function() {
var imgWidth = $("#image-hover-0").outerWidth();
var imgHeight = $("#image-hover-0").outerHeight();
$("#hover-img-0").css("width", imgWidth + "px");
$("#hover-img-0").css("height", imgHeight + "px");
$("#hover-img-0").css("line-height", imgHeight + "px");
});
});
I faced this problem before. 我以前遇到过这个问题。 But still the question is, do you want the real size?
但是问题仍然是,您想要真实的尺寸吗? or the size showed on the screen ?
还是屏幕上显示的尺寸?
For the first, you should wait the image to be loaded after you can get the real size : 首先,在获得实际大小后,应等待图像加载:
youImage.addEventListener('onload',
function() {
console.log('pic width is: ', this.naturalWidth);
console.log('pic height is: ', this.naturalHeight);
});
For the second, you must encupsle it in a div and get its size. 对于第二个,您必须将其包含在div中并获取其大小。
I hope that my answer may helps you. 希望我的回答对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.