通过边框拖放调整 div 大小,无需添加额外的标记

2024-05-01

我有一个绝对定位的侧面板,我需要通过拖动此边框来更改其宽度。我还需要更改边框悬停上的光标。是否可以在不添加另一个 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。我已经有一个了:

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 https://developer.mozilla.org/en-US/docs/Web/API/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: ew-resize;
}
<body>
    <div id="right_panel"></div>
</body>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过边框拖放调整 div 大小,无需添加额外的标记 的相关文章

随机推荐