我有一个绝对定位的侧面板,我需要通过拖动此边框来更改其宽度。另外,我需要更改边框悬停时的光标。是否可以在不添加另一个div拖动的情况下执行此操作?
这是标记:
#right_panel { position: absolute; border-left: solid 3px #ccc; width: 100px; height: 100%; right: 0; background-color: #f0f0f0; } <body> <div id="right_panel"></div> </body>
我不需要完整的解决方案。是(有文档参考)/否答案就足够了。我不需要帮手的回答div。我已经有一个:
div
var m_pos; function resize(e){ var parent = resize_el.parentNode; var dx = m_pos - e.x; m_pos = e.x; parent.style.width = (parseInt(getComputedStyle(parent, '').width) + dx) + "px"; } var resize_el = document.getElementById("resize"); resize_el.addEventListener("mousedown", function(e){ 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: #f0f0f0; } #resize { background-color: #ccc; position: absolute; left: 0; width: 4px; height: 100%; cursor: w-resize; } <body> <div id="right_panel"> <div id="resize"></div> </div> </body>
同样,这是我想要的功能,除了我想删除多余的东西div。
当然,无需额外的div就可以做到这一点。使用css和:after创建边框并更改光标。使用MouseEvent.offsetX以确定是否要处理的元素的点击。
:after
MouseEvent.offsetX
在您的示例中,您希望单击主div,但仅单击前4个像素。您可以通过检查e.offsetX < 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>