四個按鈕分別控制目標 div 的寬度 +50/-50px、高度 +50/-50px,變化即時生效,適合編輯器、儀表板面板大小調整等場景。
<script src="jquery-1.11.2.min.js"></script>
<div>
<input id="addwidthkeleyi" type="button" value="增加寬度" />
<input id="reducewidthkeleyi" type="button" value="減少寬度" />
<input id="addheightkeleyi" type="button" value="增加高度" />
<input id="reduceheightkeleyi" type="button" value="減少高度" />
點擊按鈕,注意下方 div 寬高變化
</div>
<div id="keleyidiv" style="border:1px solid #999;width:200px;height:200px"></div>
<script>
$('#addwidthkeleyi').on('click', function() {
$('#keleyidiv').width($('#keleyidiv').width() + 50);
});
$('#reducewidthkeleyi').on('click', function() {
$('#keleyidiv').width($('#keleyidiv').width() - 50);
});
$('#addheightkeleyi').on('click', function() {
$('#keleyidiv').height($('#keleyidiv').height() + 50);
});
$('#reduceheightkeleyi').on('click', function() {
$('#keleyidiv').height($('#keleyidiv').height() - 50);
});
</script>
const $box = $('#keleyidiv');
const MIN_W = 50, MAX_W = 800, MIN_H = 50, MAX_H = 600, STEP = 50;
function resize(prop, delta) {
const curr = $box[prop]();
const next = curr + delta;
if ((prop === 'width' && next < MIN_W) || (prop === 'width' && next > MAX_W) ||
(prop === 'height' && next < MIN_H) || (prop === 'height' && next > MAX_H)) return;
$box.animate({ [prop]: next }, 200, 'swing');
}
$('#addwidthkeleyi').click(() => resize('width', STEP));
$('#reducewidthkeleyi').click(() => resize('width', -STEP));
$('#addheightkeleyi').click(() => resize('height', STEP));
$('#reduceheightkeleyi').click(() => resize('height', -STEP));
const box = document.getElementById('keleyidiv');
const step = 50;
function setSize(prop, delta) {
const curr = parseInt(getComputedStyle(box)[prop]);
const next = curr + delta;
if (next < 50 || next > (prop === 'width' ? 800 : 600)) return;
box.style.transition = `${prop} 0.2s ease`;
box.style[prop] = next + 'px';
}
現代瀏覽器 getComputedStyle + CSS Transition 即可實現平滑縮放,無需 jQuery。