萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 動態改變 DIV 寬度與高度(按鈕控制即時縮放)

功能展示

四個按鈕分別控制目標 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));

原生 JS 替代方案(無依賴)


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。

copyright © 萬盛學電腦網 all rights reserved