利用HTML和Java展示矩形大小改变事件

在HTML中,可以通过JavaScript实现矩形大小的改变效果。具体步骤如下:

  1. 首先,在HTML中创建一个矩形元素,并设置其样式和初始大小:
<div id="myRectangle" style="width: 200px; height: 200px; background-color: red;"></div>
  1. 其次,在JavaScript中获取该矩形元素,并添加事件监听器,实现拖拽改变大小的效果:
var rectangle = document.getElementById('myRectangle');
rectangle.addEventListener('mousedown', function(event) {
  event.preventDefault();
  var startX = event.clientX;
  var startY = event.clientY;
  var startWidth = parseInt(window.getComputedStyle(rectangle).width);
  var startHeight = parseInt(window.getComputedStyle(rectangle).height);

  function resize(event) {
    var width = startWidth + event.clientX - startX;
    var height = startHeight + event.clientY - startY;
    rectangle.style.width = width + 'px';
    rectangle.style.height = height + 'px';
  }

  function stopResize() {
    window.removeEventListener('mousemove', resize);
    window.removeEventListener('mouseup', stopResize);
  }

  window.addEventListener('mousemove', resize);
  window.addEventListener('mouseup', stopResize);
});