【问题标题】:How to get contain size width and height?如何获得包含大小的宽度和高度?
【发布时间】:2014-07-30 17:43:28
【问题描述】:

假设我有以下html:

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

demo

这里的背景尺寸是contain,全宽和全高为100%,但是背景图片的区域没有被div完全覆盖。

那么,有没有什么办法可以得到覆盖图片的宽高呢?

【问题讨论】:

  • 计算图像原始高度和宽度的纵横比,然后使用div的高度/宽度(我认为以较小者为准),然后计算新的高度和宽度包含的图像。
  • 如果您想要图像的尺寸,请在<div> 元素中使用<img> 元素。然后你可以使用 javascript 来获取尺寸。
  • @SamyS.Rathore 你能举个例子吗?
  • @Mr_Green 不,我不能使用。

标签: javascript jquery css viewport


【解决方案1】:

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}));

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

【讨论】:

  • 我刚刚查看了这个并认为有一些错误,即使在横向模式下,areaWidth 也可能大于 imageWidth 但您分配的是 imageWidth = areaWidth ,对吗??
  • 我的意思是,在横向模式下,初始尺寸图像的宽度小于视口区域。
  • 我的意思是 areaWidth 是 100% 但 imageWidth 不是,对吧?如果你确定,可以给我演示一下吗?
  • 我想我理解错了。您的意思是 areaWidth 是视口宽度还是其他?如果是视口宽度,怎么能等于 imageWidth?
  • @C-link 我的意思是areaWidth$('div').width(),即区域是您定义背景图像的块。
【解决方案2】:

编辑::

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;

【讨论】:

  • 不回答是 OP 的问题 那么,有什么方法可以获取覆盖图像的宽度和高度吗?
  • 如果 width > height 那么 imgWidth 没问题,但如果 width
  • 在宽度 width 重新计算? actualImgHeight/actualImgWidth * width : height;
【解决方案3】:

使用下面的 CSS :

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    相关资源
    最近更新 更多