要制作一个可调整大小的矩形选择工具,您可以使用HTML、CSS和JavaScript来实现。以下是一个简单的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Resizable Rectangle Tool</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<div class="rectangle" id="rectangle">
<div class="handler handler-top"></div>
<div class="handler handler-right"></div>
<div class="handler handler-bottom"></div>
<div class="handler handler-left"></div>
</div>
</div>
<script src="scripts.js"></script>
</body>
</html>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
.container {
width: 50%;
height: 50%;
position: relative;
background-color: #ffffff;
}
.rectangle {
width: 50%;
height: 50%;
position: absolute;
border: 2px solid #000000;
display: flex;
justify-content: center;
align-items: center;
}
.handler {
position: absolute;
width: 10px;
height: 10px;
background-color: #000000;
cursor: pointer;
}
.handler-top {
top: -5px;
left: 50%;
transform: translateX(-50%);
}
.handler-right {
right: -5px;
top: 50%;
transform: translateY(-50%);
}
.handler-bottom {
bottom: -5px;
left: 50%;
transform: translateX(-50%);
}
.handler-left {
left: -5px;
top: 50%;
transform: translateY(-50%);
}
const rectangle = document.getElementById('rectangle');
const handlers = document.querySelectorAll('.handler');
handlers.forEach(handler => {
handler.addEventListener('mousedown', (e) => {
const startX = e.clientX;
const startY = e.clientY;
const startWidth = parseInt(rectangle.style.width);
const startHeight = parseInt(rectangle.style.height);
const onMouseMove = (e) => {
let width = startWidth + e.clientX - startX;
let height = startHeight + e.clientY - startY;
if (width < 50) width = 50;
if (height < 50) height = 50;
rectangle.style.width = width + 'px';
rectangle.style.height = height + 'px';
};
const onMouseUp = () => {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
};
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
});
});
这个示例中,我们使用HTML和CSS创建了一个可调整大小的矩形,并使用JavaScript实现了调整大小的功能。您可以根据需要进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云