如何获得包含尺寸的宽度和高度?

问题描述 投票:11回答:3

假设我有以下html:

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

demo

在这里,背景尺寸包含在内,并且是宽度和高度的100%,但是div不能完全覆盖背景图像的区域。

所以,有什么方法可以获取所覆盖图像的宽度和高度吗?

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9PSHBFUS5qcGcifQ==” alt =“在此处输入图像描述”>

javascript jquery css viewport
3个回答
7
投票

documentation提到有关contain的以下内容:

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

这将解决以下代码(ES6):

function contain({width: imageWidth, height: imageHeight}, {width: areaWidth, height: areaHeight}) {
  const imageRatio = imageWidth / imageHeight;

  if (imageRatio >= areaWidth / areaHeight) {
    // longest edge is horizontal
    return {width: areaWidth, height: areaWidth / imageRatio};
  } else {
    // longest edge is vertical
    return {width: areaHeight * imageRatio, height: areaHeight};
  }
}

console.log(1, contain({width: 15, height: 60}, {width: 20, height: 50}));
console.log(2, contain({width: 15, height: 60}, {width: 50, height: 20}));
console.log(3, contain({width: 60, height: 15}, {width: 20, height: 50}));
console.log(4, contain({width: 60, height: 15}, {width: 50, height: 20}));
console.log(5, contain({width: 40, height: 20}, {width: 50, height: 20}));

根据图像方向(人像或风景),它首先增长最长的边缘,然后在必要时缩小最短的边缘,同时仍保持宽高比。


0
投票

在CSS下方使用:

div{
    background: url("Your Image Path") no-repeat;
    width: 100%;
    height: 100%;
    background-position: center;
    background-size: 100% auto;
  }

0
投票

编辑::

var width = $('.demo').width(); //demo is div class name
var height = $('.demo').height();

// if width > height
var imgWidth = width > height ? actualImgWidth/actualImgHeight * height : width;
//if width < height
var imgHeight = height > width ? actualImgHeight/actualImgWidth * width : height;
© www.soinside.com 2019 - 2024. All rights reserved.