【问题标题】:How to resize parent by dragging one of it's children?如何通过拖动其中一个孩子来调整父母的大小?
【发布时间】:2017-06-24 12:24:48
【问题描述】:

基本上我想通过拖动蓝色的东西来调整绿色框的大小。

我正在尝试使用OffsetLeft,但无法正常工作。在 Firefox 中也不会触发拖动事件。

我这里有代码:jsbin link

<div id="parent">
   
 <div draggable="true" id="child" ondrag="dragging(event)" ></div>
 
</div>

<script>
   const parent = document.getElementById('parent');
   const child = document.getElementById('child');

   function dragging(event) {
     console.log("dragging");
     parent.style.width = child.offsetLeft;
   }

 </script>

和css:

/* green box */
#parent{
  position:absolute; -- notice the parent is absolute positioned. (not sure if it has an impact on how it works - but i need it to be absolute.
  top: 100;
  left: 100;
  background-color: green;
  height: 100px;
  width: 100px;
  display: flex;
  justify-content: flex-end;
}

/* blue bar */
#child{
  width: 5px;
  background-color: blue;
  cursor: e-resize;
}

那么我怎么能做到这一点,同时也是cross-browser compatible? 我需要html5 + js 解决方案 - 因为我将使用另一种名为elm 的编程语言的逻辑。我只能从 DOM 中读取内容,不能对其进行变异。所以我不能使用已经构建的库,比如 Jquery。

感谢您的关注。

【问题讨论】:

  • 主要问题是你还需要添加一个单元,像这样child.offsetLeft + 'px';
  • @LGSon 哈哈,很好,谢谢。通用方法仍然很糟糕,因为拖动蓝线 - 根本不会改变 offsetLeft - 这是反直觉的 - 我需要一种不同的方法。
  • 你应该使用event.pageX ...发布了一个答案,现在正在检查为什么FF不会一起玩

标签: html drag-and-drop draggable drag


【解决方案1】:

您应该使用event.pageX 来获得正确的值(并使用单位:)

这不适用于 Firefox:https://bugzilla.mozilla.org/show_bug.cgi?id=505521

const parent = document.getElementById('parent');
const child = document.getElementById('child');

function dragging(event) {
  console.log("dragging");
  parent.style.width = event.pageX + 'px';
}

function dragStart(event) {
  event.dataTransfer.setData("Text", event.target.id);
}
/* green box */

#parent {
  position: absolute;
  top: 100;
  left: 100;
  background-color: green;
  height: 100px;
  width: 100px;
  display: flex;
  justify-content: flex-end;
}


/* blue bar */

#child {
  width: 5px;
  background-color: blue;
  cursor: e-resize;
}
<div id="parent">

  <div draggable="true" id="child" ondragstart="dragStart(event)" ondrag="dragging(event)"></div>

</div>
<div id="demo"></div>

不过,老式的方式也可以在 Firefox 中使用:create-a-draggable-div-in-native-javascript

【讨论】:

  • 我喜欢你的回答 - 但我需要一个跨浏览器解决方案。在选择接受的答案之前,我会再等一会儿。
  • @AIon 更新了我的答案,提供了另一个帖子的链接,显示了拖动元素的旧时尚方式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
  • 1970-01-01
  • 2014-09-24
  • 1970-01-01
  • 2017-08-30
  • 2014-07-15
相关资源
最近更新 更多