如何获得包含大小的宽度和高度?

Bho*_*yar 11 javascript css jquery viewport

假设我有以下html:

html,body{
    height: 100%;
    overflow-y: hidden;
}
div{
    background: url(path) no-repeat center;
    width: 100%;
    height: 100%;
    background-size: contain;
}
Run Code Online (Sandbox Code Playgroud)

演示

这里,background-size包含并且是100%的全宽和高度,但div没有完全覆盖背景图像的区域.

那么,有没有办法获得被覆盖图像的宽度和高度?

在此输入图像描述

Ja͢*_*͢ck 6

文档提到了以下内容contain:

此关键字指定应将背景图像缩放到尽可能大,同时确保其尺寸小于或等于背景定位区域的相应尺寸.

这将适用于以下代码:

imageRatio = imageWidth / imageHeight;

if (imageRatio >= 1) { // landscape
    imageWidth = areaWidth;
    imageHeight = imageWidth / imageRatio;
    if (imageHeight > areaHeight) {
        imageHeight = areaHeight;
        imageWidth = areaHeight * imageRatio;
    }
} else { // portrait
    imageHeight = areaHeight;
    imageWidth = imageHeight * imageRatio;
    if (imageWidth > areaWidth) {
        imageWidth = areaWidth;
        imageHeight = areaWidth / imageRatio;
    }
}
Run Code Online (Sandbox Code Playgroud)

根据图像方向(纵向或横向),它首先生长最长边,然后在必要时缩小最短边,同时仍然保留纵横比.