当然,无需额外的div就可以做到这一点。使用css和
:after创建边框并更改光标。使用
MouseEvent.offsetX以确定是否要处理的元素的点击。
在您的示例中,您希望单击主div,但仅单击前4个像素。您可以通过检查
e.offsetX < 4点击处理程序来做到这一点:
const BORDER_SIZE = 4;const panel = document.getElementById("right_panel");let m_pos;function resize(e){ const dx = m_pos - e.x; m_pos = e.x; panel.style.width = (parseInt(getComputedStyle(panel, '').width) + dx) + "px";}panel.addEventListener("mousedown", function(e){ if (e.offsetX < BORDER_SIZE) { m_pos = e.x; document.addEventListener("mousemove", resize, false); }}, false);document.addEventListener("mouseup", function(){ document.removeEventListener("mousemove", resize, false);}, false);#right_panel { position: absolute; width: 96px; padding-left: 4px; height: 100%; right: 0; background-color: #f0f0ff;}#right_panel:after { content: " "; background-color: #ccc; position: absolute; left: 0; width: 4px; height: 100%; cursor: w-resize;}<body> <div id="right_panel"></div></body>


