【问题标题】:Problem resizing element that's a fixed position from the right调整从右侧固定位置的元素大小时出现问题
【发布时间】:2019-04-08 05:18:30
【问题描述】:

我有一个 div,它从窗口右侧的固定位置开始,但它是可拖动的(使用 javascript)和可调整大小的(使用 css)。问题是,如果首先调整 div 的大小(通过抓住右下角),它将无法正确调整大小。它将从右侧保持其固定位置,然后从左侧增大或缩小。但是,如果先拖动 div,则调整大小将按预期工作。这些是当前 div 的 css 属性:

#resize {
  position: fixed;
  right: 30px;
  height: 90px;
  width: 90px;
  background-color: blue;
  resize: both;
  overflow: auto;
}

演示:

https://jsfiddle.net/mravdo52/2/

我尝试了各种解决方法。由于似乎 div 的移动使resize 正常工作,我尝试在加载元素后将 div 移动一个像素,但这不起作用,因为我认为加载之间存在时间问题元素、javascript 的执行和 css 的负载。我随后尝试使用 jQuery promise()queue() 先应用 css,然后移动元素,但这些也不起作用。我也尝试过使用 jQuery UI resizable(),但这似乎根本没有调整大小。在这一点上我没有想法,希望能提供任何帮助。

【问题讨论】:

  • 遇到了问题,但它的表现应该如何?

标签: css resize css-position draggable


【解决方案1】:

仅 CSS 解决方案: 您只需要将 初始分配给固定位置的 div。

解决方案说明: 拖动元素后工作的原因是因为它申请了左位置,所以我们可以在拖动元素之前给左位置,它会工作!

首先尝试提供left: auto/initial/inherit,但没有成功。 所以你可以这样写:left: calc(100% - 120px);

(120px代表右边位置30px和div宽度90px之和)

#resize {
  position: fixed;
  right: 30px;
  left: calc(100% - 120px);
  height: 90px;
  width: 90px;
  background-color: blue;
  resize: both;
  overflow: auto;
  min-width: 90px;
  min-height: 90px;
  max-width: calc(100% - 60px);
  max-height: calc(100vh - 50px);
}

dragElement(document.getElementById("resize"));

function dragElement(elmnt) {
  var pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;
  if (document.getElementById("drag")) {
    document.getElementById("drag").onmousedown = dragMouseDown;
  } else {
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
#resize {
  position: fixed;
  right: 30px;
  height: 90px;
  width: 90px;
  background-color: blue;
  resize: both;
  overflow: auto;
  min-width: 90px;
  min-height: 90px;
  max-width: calc(100% - 60px);
  max-height: calc(100vh - 50px);
}

#drag {
  background-color: red;
  height: 20px;
}
<div id="resize">
  <div id="drag">
  </div>
</div>

更新小提琴:https://jsfiddle.net/mravdo52/6/

【讨论】:

    猜你喜欢
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多