<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录窗口示例</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<div class="window">
<div class="header">
<span>登录窗口</span>
<button class="close-button">X</button>
</div>
<div class="content">
<input type="text" placeholder="用户名">
<input type="password" placeholder="密码">
<button>登录</button>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
css:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f5f5f5;
}
.container {
position: relative;
width: 320px;
background-color: #fff;
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.window {
position: absolute;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 20px;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding-bottom: 20px;
border-bottom: 1px solid #ccc;
}
.close-button {
cursor: pointer;
font-size: 24px;
}
.content {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
input {
padding: 10px;
margin: 10px 0;
width: 100%;
border: 1px solid #ccc;
border-radius: 4px;
outline: none;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
JS:
const container = document.querySelector('.container');
const windowEl = document.querySelector('.window');
const closeButton = document.querySelector('.close-button');
let isDragging = false;
let startX;
let startY;
let deltaX;
let deltaY;
container.addEventListener('mousedown', (e) => {
if (e.target === closeButton) return;
isDragging = true;
startX = e.clientX - windowEl.getBoundingClientRect().left;
startY = e.clientY - windowEl.getBoundingClientRect().top;
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
deltaX = e.clientX - startX;
deltaY = e.clientY - startY;
const maxWidth = document.body.clientWidth - windowEl.clientWidth;
const maxHeight = document.body.clientHeight - windowEl.clientHeight;
windowEl.style.left = Math.min(maxWidth, Math.max(0, deltaX)) + 'px';
*** = Math.min(maxHeight, Math.max(0, deltaY)) + 'px';
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
closeButton.addEventListener('click', () => {
windowEl.style.display = 'none';
});