可手动调整图片大小,并实时更新记录图片宽高。
needRat 控制是否按图片原本尺寸缩放
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.resizeImg{
width: 100%!important;
height: 100%!important;
}
.resizeDiv{
margin: 50px auto;
font-size: 0;
resize: both;
overflow: hidden;
width: 200px;
/* 初始宽度 */
max-width: 800px;
max-height: 800px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div class="resizeDiv" >
<img class="resizeImg" src="https://ts1.cn.mm.bing.net/th?id=OIP-C.7KW5GT7NQ8yUGlBbCHEm0gHaNK&w=187&h=333&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2">
</div>
<script>
let needRat = true;// 是否等比缩放
let fn = ()=>{
document.querySelectorAll('.resizeImg').forEach(v=>{
if(!v.style.width || !needRat){
v.style.width = v.width + 'px';
v.style.height = v.height + 'px';
if(needRat){
v.style.objectFit = 'contain';
}else{
v.style.objectFit = 'fill'
}
}else{
v.style.objectFit = 'contain';
let rat = v.naturalHeight/v.naturalWidth;
if(v.height/v.width > rat){
v.style.width = v.width + 'px';
v.style.height = Math.round(v.width*rat) + 'px';
v.parentElement.width = v.width + 'px';
v.parentElement.style.height = Math.round(v.width*rat) + 'px';
}else{
v.style.height = v.height + 'px';
v.style.width = Math.round(v.height/rat) + 'px';
v.parentElement.style.height = v.height + 'px';
v.parentElement.style.width = Math.round(v.height/rat) + 'px';
}
}
})
}
let timer;
const resizeObserver = new ResizeObserver((entries) => {
if(timer){
clearTimeout(timer)
}
timer = setTimeout(() => {
fn()
}, 800)
})
resizeObserver.observe(document.querySelector(`.resizeDiv`))
</script>
</body>
</html>