如何通过拖动其中一个孩子来调整父级的大小? [英] How to resize parent by dragging one of it's children?

查看:179
本文介绍了如何通过拖动其中一个孩子来调整父级的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Essentially i want to resize the green box by dragging the blue thing.

我正在尝试使用 OffsetLeft 但不起作用。 Firefox中也没有触发拖动事件。

I'm trying to use OffsetLeft but is not working. also the drag event doesn't fire in Firefox.

我的代码在这里: jsbin链接

<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;
}

那我怎么能这样做,也是跨浏览器兼容
我需要一个 html5 + js 解决方案 - 因为我会将这个逻辑用于另一种名为 elm 的编程语言。我只能从DOM中读取内容,而不是改变它。所以我无法使用像Jquery这样已经构建的库。

So how can i do this, and also be cross-browser compatible? I need a html5 + js solution - because i will use the logic for another programming language called elm. I can only read stuff form the DOM, not mutate it. So I can't work with already built libraries like Jquery.

感谢您的关注。

推荐答案

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

You should use event.pageX to get the correct value (and use a unit :)

这对Firefox不起作用: https://bugzilla.mozilla.org/show_bug.cgi?id=505521

This won't work on Firefox though: 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

The old fashion way will work in Firefox though: create-a-draggable-div-in-native-javascript

这篇关于如何通过拖动其中一个孩子来调整父级的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆