我正在构建窗口调整大小功能。我已经尝试过自己,但是当我尝试抓住并拖动手柄时,窗户移动得太快。
(function () {
const d = {};
document.addEventListener("mousedown", (e) => {
const container = e.target.closest(".container");
if (container != null && e.target.classList.contains("handle")) {
d.el = container;
d.div1 = container.children[0];
d.handle = container.children[1];
d.div2 = container.children[2];
d.mouseStartX = e.clientX;
d.elStartX = d.el.getBoundingClientRect().left;
d.handle.style.background = "rgb(100, 100, 100)";
document.body.style.userSelect = "none";
document.body.style.cursor = "e-resize";
}
});
document.addEventListener("mousemove", (e) => {
if (d.el === undefined) {
return;
}
d.div1.style.width =
d.div1.offsetWidth + (e.clientX - d.mouseStartX) + "px";
});
document.addEventListener("mouseup", (e) => {
if (d.el === undefined) {
return;
}
d.handle.style.background = "rgb(58, 58, 58)";
document.body.style.userSelect = "";
document.body.style.cursor = "";
d.el = undefined;
});
})();
.container {
display: flex;
}
.div1,
.div2 {
border: 1px solid;
height: 300px;
width: 300px;
}
.handle {
cursor: e-resize;
width: 4px;
background: #424242;
display: flex;
justify-content: center;
align-items: center;
transition: all 0.2s ease-in-out;
color: #fff;
}
<div class="container">
<div class="div1">wer</div>
<div class="handle">|</div>
<div class="div2">sdf</div>
</div>
我尝试过
d.div1.style.width = document.body.scrollWidth - e.clientX
和
d.div1.style.width = d.div1.offsetWidth + (e.clientX - d.mouseStartX - d.elStartX)
用于mousemove
事件侦听器中的宽度公式,但均无效。
答案 0 :(得分:2)
offsetWidth导致其速度增加了一倍。如果您在一开始就获得了它的价值;
(function () {
const d = {};
document.addEventListener("mousedown", (e) => {
const container = e.target.closest(".container");
if (container != null && e.target.classList.contains("handle")) {
d.el = container;
d.div1 = container.children[0];
d.handle = container.children[1];
d.div2 = container.children[2];
d.mouseStartX = e.clientX;
d.elStartX = d.el.getBoundingClientRect().left;
d.handle.style.background = "rgb(100, 100, 100)";
document.body.style.userSelect = "none";
document.body.style.cursor = "e-resize";
}
});
var ofs = null
document.addEventListener("mousemove", (e) => {
if (d.el === undefined) {
return;
}
if(ofs === null){
ofs = d.div1.offsetWidth
}
d.div1.style.width =
ofs + (e.clientX - d.mouseStartX) + "px";
});
document.addEventListener("mouseup", (e) => {
if (d.el === undefined) {
return;
}
d.handle.style.background = "rgb(58, 58, 58)";
document.body.style.userSelect = "";
document.body.style.cursor = "";
d.el = undefined;
});
})();
.container {
display: flex;
}
.div1,
.div2 {
border: 1px solid;
height: 300px;
width: 300px;
}
.handle {
cursor: e-resize;
width: 4px;
background: #424242;
display: flex;
justify-content: center;
align-items: center;
transition: all 0.2s ease-in-out;
color: #fff;
}
<div class="container">
<div class="div1">wer</div>
<div class="handle">|</div>
<div class="div2">sdf</div>
</div>
将以相同的速度前进。