假设我有以下 html:
html,body{
height: 100%;
overflow-y: hidden;
}
div{
background: url(path) no-repeat center;
width: 100%;
height: 100%;
background-size: contain;
}
这里,background-size是contain,全宽和全高都是100%,但是背景图片的区域没有被div完全覆盖。
那么,有没有什么办法可以得到被覆盖图片的宽高呢?
最佳答案
documentation提到以下关于contain
的内容:
This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.
这将适用于以下代码 (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}));
根据图像方向(纵向或横向),它首先增加最长的边缘,然后在必要时收缩最短的边缘,同时仍保持纵横比。
关于javascript - 如何获得包含尺寸的宽度和高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24132902/