<p>{&quot;title&quot;:&quot;JavaScript实现矩形拖动并按住Shift键等比例缩放&quot;,&quot;description&quot;:&quot;本文介绍如何使用JavaScript实现拖动矩形并按住Shift键进行等比例缩放。代码示例包含HTML、CSS和JavaScript,并提供详细的解释。&quot;,&quot;keywords&quot;:&quot;JavaScript, 拖动, 矩形, 等比例缩放, Shift键, 鼠标事件, 代码示例&quot;,&quot;content&quot;:&quot;&lt;div id=&quot;rectangle&quot;&gt;</div>\n<style>#rectangle {\n  background-color: red;\n  width: 100px;\n  height: 100px;\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  cursor: move;\n}\n</style>\n<script>var rectangle = document.getElementById('rectangle');\nvar isDragging = false;\nvar startX, startY, startWidth, startHeight;\n\n// 按下鼠标按钮时开始拖动\nrectangle.addEventListener('mousedown', function (event) {\n  if (event.shiftKey) {\n    isDragging = true;\n    startX = event.clientX;\n    startY = event.clientY;\n    startWidth = parseInt(window.getComputedStyle(rectangle).width);\n    startHeight = parseInt(window.getComputedStyle(rectangle).height);\n  }\n});\n\n// 松开鼠标按钮时停止拖动\ndocument.addEventListener('mouseup', function () {\n  isDragging = false;\n});\n\n// 移动鼠标时进行拖动和缩放\ndocument.addEventListener('mousemove', function (event) {\n  if (isDragging) {\n    var deltaX = event.clientX - startX;\n    var deltaY = event.clientY - startY;\n    var newWidth = startWidth + deltaX;\n    var newHeight = startHeight + deltaY;\n\n    // 按住 Shift 键时等比例缩放\n    if (event.shiftKey) {\n      var ratio = startWidth / startHeight;\n      if (deltaX &gt; deltaY) {\n        newHeight = newWidth / ratio;\n      } else {\n        newWidth = newHeight * ratio;\n      }\n    }\n\n    rectangle.style.width = newWidth + 'px';\n    rectangle.style.height = newHeight + 'px';\n  }\n});\n</script>\n\n在上述代码中,我们首先获取了矩形元素和一些初始参数。当鼠标按下时,我们将 <code>isDragging</code> 设置为 <code>true</code>,并记录下起始点的坐标和矩形的初始宽度和高度。然后,在鼠标移动时,我们根据移动的距离计算出新的宽度和高度,并将其应用于矩形元素。如果同时按下 Shift 键,我们会根据移动的水平和垂直距离来调整宽度和高度,以保持等比例缩放。\n\n请注意,此代码仅实现了矩形的拖动和等比例缩放功能,您可能需要根据自己的需求进行适当的调整和修改。&quot;}</p>

原文地址: https://www.cveoy.top/t/topic/pSDQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录