问题
Essentially i want to resize the green box by dragging the blue thing.
I'm trying to use OffsetLeft
but is not working. also the drag event doesn't fire in Firefox.
And i have the code here: 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>
and 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;
}
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.
Thanks for your interest.
回答1:
You should use event.pageX
to get the correct value (and use a unit :)
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>
The old fashion way will work in Firefox though: create-a-draggable-div-in-native-javascript
来源:https://stackoverflow.com/questions/44736344/how-to-resize-parent-by-dragging-one-of-its-children