图像高度与图像宽度成比例,但图像宽度以父项的百分比为单位



我希望你能帮我:)

我想定义img的高度,相对于图像的"实际"宽度。但是宽度是动态的,因为它位于父对象的 % 中(wxample 的浏览器窗口)。

为什么我需要高度?没有高度,它可以正常工作,但我需要它,因为我希望所有图片的顶部在顶部相遇,并且我的照片具有不同的比例。(我知道这会压缩图片...后来我用溢出解决这个问题,在我有高度问题的解决方案之后)。

如何想象,我需要一些东西来返回我"实际"(例如,在用户更改浏览器窗口大小后)宽度的 px。然后我可以把它乘以 3 并将其写到高度。(比例为1比3)

这应该可以满足你所需要的一切。

var img = document.getElementById('testImage');
// these vars are numbers representing a length in pixel
var w = img.width, h = img.height; // displayed dimensions, change on resize
var nw = img.naturalWidth, nh = img.naturalHeight; // dimensions of the original image file
var proportion = nh / nw; // proportion < 1 : 'portrait', < 1 : 'landscape'

由于宽度/高度在调整大小时会发生变化,因此您必须在需要时更新它们。

最新更新