在项目中,特别是移动端我们经常要做一些图片展示的功能,楼主在一年前基于better-scroll封装了类似微信朋友圈图片查看的功能
我们不能给图片设置固定的宽高和宽度撑满,这样简单粗暴的方法,应该根据图片宽高比例和容器宽高比例进行图片宽高的设置
js动态计算
1、容器宽高比例 > 图片宽高比例 说明图片比较高 以高度为准
2、容器宽高比例 < 图片宽高比例 说明图片比较宽 以宽度为准
css背景属性
background-size: contain;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div + div {
margin-top: 30px;
}
.img-container{
width:688px;
height:304px;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
box-sizing: border-box;
background: black;
}
.img-container1{
width:688px;
height:304px;
background: black url(./test.png) no-repeat center center;
background-size: contain;
}
.width {
width: 668px;
height: 404px;
}
.height {
width: 668px;
height: 204px;
}
.equal{
width:344px;
height:152px;
}
</style>
</head>
<body>
<div class="img-container">
</div>
<div class="img-container1"></div>
<script>
const container = document.querySelector(".img-container")
const container1 = document.querySelector(".img-container1")
container.classList.add("width")
container1.classList.add("width")
// container.classList.add("height")
// container1.classList.add("height")
// container.classList.add("equal")
// container1.classList.add("equal")
const url = './test.png';
const img = document.createElement("img")
img.src = url;
img.onload=function(){
console.log(container.offsetWidth,container.offsetHeight,img.width,img.height) //688 304
let {width,height} = getRealSize(container.offsetWidth,container.offsetHeight,img.width,img.height, 1)
console.log(width,height)
img.width = width
img.height = height
}
container.appendChild(img)
/**
* [获取自适应图片的宽高]
* @param {[number]} parentWidth [父容器宽]
* @param {[number]} parentHeight [父容器高]
* @param {[number]} imgWidth [图片实际宽]
* @param {[number]} imgHeight [图片时间高]
* @param {[number]} radio [撑开比例]
* @return {[Obejt]} [图片真实宽高]
*/
function getRealSize(parentWidth, parentHeight, imgWidth, imgHeight, radio){
let real = {width:0,height:0}
let scaleC = parentWidth / parentHeight;
let scaleI = imgWidth / imgHeight;
if(scaleC > scaleI){ //说明图片比较高 以高度为准
console.log("height")
real.height = radio * parentHeight;
real.width = parentHeight * scaleI;
}else if(scaleC < scaleI){ //说明图片比较宽 以宽度为准
console.log("width")
real.width = radio * parentWidth;
real.height = parentWidth / scaleI;
}else{
real.width = radio * parentWidth;
real.height = parentWidth / scaleI;
}
return real
}
</script>
</body>
</html>
object-fit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.img-container{
width:688px;
height:204px;
background: black;
}
.img-container img{
width: 100%;
height: 100%;
object-fit: contain;
}
</style>
</head>
<body>
<div class="img-container">
<img src="./test.png" alt="">
</div>
<script>
</script>
</body>
</html>
对比
对比这三种方式,其实第二种background-size
和object-fit
都是利用contain,将容器按比例撑满
但是js动态计算可以设置撑满的比例,比如我不希望按高度计算的时候全部撑满,上下留点间隙,那么使用getRealSize函数radio参数就可以做到