使用scale
對表格進行縮放 出現大片空白問題
一直沒有很好地重視這個問題,導致這次不得不面對,經過各種搜索,各種嘗試,終於解決了這個留白問題
思路
大小盒子,小盒子進行縮放,大盒子依據縮放來進行動態更改高寬
//style 樣式
.box {
position: relative;
margin: 20px auto;
width: 400px;
border: 5px dashed #777;
background-color: #ccc;
}
.dv {
position: relative; //子盒子也為相對定位 這樣可以撐開父盒子 特別是動態渲染時
left: 50%;
transform: translateX(-50%);
width: 550px;
height: 300px;
background-color: skyblue;
}
#btn {
width: 150px;
height: 50px;
border: none;
color: '#333';
font-size: 16px;
background-color: #0ff;
}
// html
<div class="box">
<div class="dv"><span>我的天空</span></div>
</div>
<button id="btn">點擊切換</button>
//js
function $(name) {
return document.querySelector(name)
}
const boxWidth = $('.box').offsetWidth,
dvWidth = $('.dv').offsetWidth,
boxHeight = $('.box').offsetHeight,
dvHeight = $('.dv').offsetHeight
const scale = boxWidth / dvWidth
// 關鍵部位 高度縮放 對父盒子進行高度縮放,這樣就不會有留白的
// dv縮放后實際的高度
const dvScaleHeight = dvHeight * scale
// 父盒子縮放的高度
const boxScale = dvScaleHeight / boxHeight
$('#btn').onclick = function() {
$('.dv').style.transform = `scale(${scale}) translateX(-50%)`
$('.dv').style.transformOrigin = `0 top`
$('.box').style.height = boxHeight * boxScale + 'px'
}
效果圖
未縮放前的原始效果
縮放后的效果 沒有空白