我正在制作 Chrome 扩展程序。我试图让弹出窗口可拖动并能够在屏幕上移动。我可以移动它,但它卡在屏幕右侧,直到到达max-width
。我做错了什么?
这是简化的代码。
const popup = document.getElementById("popup");
const dragBtn = document.getElementById("drag-btn");
let offsetX, offsetY, isDragging = false;
dragBtn.addEventListener("mousedown", (e) => {
isDragging = true;
offsetX = e.clientX - popup.offsetLeft;
offsetY = e.clientY - popup.offsetTop;
});
document.addEventListener("mousemove", (e) => {
if (isDragging) {
popup.style.left = `${e.clientX - offsetX}px`;
popup.style.top = `${e.clientY - offsetY}px`;
}
});
document.addEventListener("mouseup", (e) => {
isDragging = false;
});
#popup {
position: fixed;
top: 20px;
right: 20px;
min-width: 350px;
max-width: 500px;
background: var(--dark-bg, #222);
color: var(--dark-text, #fff);
border: 1px solid #333;
box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.4);
padding: 15px;
border-radius: 8px;
z-index: 10000;
}
#popup-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
#popup-title {
font-size: 14px;
font-weight: bold;
}
button {
border: none;
cursor: pointer;
border-radius: 4px;
font-size: 16px;
width: 26px;
height: 26px;
text-align: center;
padding: 0;
}
#drag-btn {
background: #326042;
color: white;
cursor: grab;
}
#theme-btn {
background: #ef713b;
color: white;
}
#close-btn {
background: #ff5252;
color: white;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Song Lyrics Finder</title>
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<div id="popup">
<div id="popup-header">
<p id="popup-title">Song Lyrics Finder (from Genius.com)</p>
<div style="display: flex; align-items: center; gap: 5px;">
<button id="drag-btn">✥</button>
<button id="theme-btn">◑</button>
<button id="close-btn">⮿</button>
</div>
</div>
</div>
</body>
</html>
因为元素有一个
right
值,并且您正在更改该left
值,所以您正在拉伸该元素直到其达到最大尺寸。我会改用变换来改变位置。除了不影响元素的宽度外,性能通常也更好(参见此SO 答案):
另一个选项是重置
right
并auto
设置当前鼠标按下事件,因为我们将从现在left
开始更新:left