简体   繁体   English

如何获得具有自动高度的100%宽度图像的高度?

[英]How to get height of a 100% width image with auto height?

In this case, I set an image with width: 100% and height: auto (actual image size is 362x614). 在这种情况下,我将图像的width: 100%设置为width: 100%height: auto设置为height: auto (实际图像尺寸为362x614)。 I need to get height of image for another step. 我需要获取图像的高度,用于下一步。

Here is my code: 这是我的代码:

<img class="phone" src="img/phone2.png">

and js: 和js:

$(document).ready(function() {
   phoneSlider();
});

$(window).resize(function(){
   phoneSlider()
});

function phoneSlider(){
   var phoneMaskWidth = $(".phone").width();
   var phoneMaskHeight = $(".phone").height();
       console.log(phoneMaskWidth + "|" + phoneMaskHeight);
       .......
}

Then, I check in the console, and the result: 362|0 . 然后,我在控制台中检入结果: 362|0 Why is phoneMaskHeight showing 0 and how can I get the real height? 为什么phoneMaskHeight显示为0,如何获得实际高度?

use: 采用:

var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = $(".phone").attr('src');

Working Fiddle 工作小提琴

Move your code from $(document).ready() to $(window).load() . 将您的代码从$(document).ready()移至$(window).load() The browser needs to load the image (or at least the image header) before it can calculate its width and height. 浏览器需要先加载图像(或至少图像标题),然后才能计算其宽度和高度。 Document ready event can fire before the browser has chance to have a look at the image. 在浏览器有机会查看图像之前 ,可能会触发文档就绪事件。

Demo here ; 演示在这里 ; change the image source (or empty browser cache), run and look at the console 更改图像源(或清空浏览器缓存),运行并查看控制台

$("img.phone").on('load', function() { alert( this.height ); });

这对我有用。

Browsers load images asynchronously and until the image is fully loaded its height will be unknown. 浏览器异步加载图像,直到完全加载图像为止,其高度是未知的。

As others have suggested you will need to attach your code to the "onload" event that is fired when the image is loaded, but that will force you to change your whole phoneSlider method. 正如其他人所建议的那样,您需要将代码附加到加载图像时触发的“ onload”事件,但这将迫使您更改整个phoneSlider方法。 You will need to put everything that depends on the height of the image in the corresponding onload callback. 您需要将所有取决于图像高度的内容放入相应的onload回调中。

If you don't need to do your calculation as soon as the image is loaded, the Salman A's answer is the better approach - put your logic when the window#onload event is fired, this ensures all external resources (including images) are loaded. 如果您不需要在加载图像后立即进行计算,则Salman A的答案是更好的方法-在触发window#onload事件时放置您的逻辑,这样可确保加载所有外部资源(包括图像) 。

$(document).ready(function(){ $(文件)。就绪(函数(){
console.log($('#myimg').width() + 'x' + $('#myimg').height()); console.log($('#myimg')。width()+'x'+ $('#myimg')。height());

console.log($("#myimg").attr('src')); 的console.log($( “#myimg”)ATTR( 'SRC'));

}) })

working demo [http://jsfiddle.net/A5QJM/238/] 工作演示[http://jsfiddle.net/A5QJM/238/]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM