假设我有以下html:
html,body{
height: 100%;
overflow-y: hidden;
}
div{
background: url(path) no-repeat center;
width: 100%;
height: 100%;
background-size: contain;
}
在这里,背景尺寸包含在内,并且是宽度和高度的100%,但是div不能完全覆盖背景图像的区域。
所以,有什么方法可以获取所覆盖图像的宽度和高度吗?
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9PSHBFUS5qcGcifQ==” alt =“在此处输入图像描述”>
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}));
根据图像方向(人像或风景),它首先增长最长的边缘,然后在必要时缩小最短的边缘,同时仍保持宽高比。
在CSS下方使用:
div{
background: url("Your Image Path") no-repeat;
width: 100%;
height: 100%;
background-position: center;
background-size: 100% auto;
}
编辑::
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;