问题
I am working with two divs where, one in the left is a collapsible container and the one in the right is a main container, something like this:
================================
| | |
| | |
| | |
| div 1 | div 2 |
| | |
| | |
================================
I am collapsing div 1 using simple css class and when div 1 is not visible, div 2 expands in size and takes over rest of the space. Now I need to get the size of the div 2 once it is done with the resizing (which is not instant and it is using transition).
I want to render d3 stuff in div 2 and need to to know the correct dimension of the div. Unfortunately,
$("#div2-id").width()
is returning undefined result. I think it is mainly due to the transition. How can I get correct width and height of the div after resizing is done?
回答1:
Read this post as I believe is a more accurate approach, as you fire an event as soon as the transition ends. Callback when CSS3 transition finishes
回答2:
I'd try using a timeout with the duration of the transition.
var delay = 2000;
var t = setTimeout(function(){
var width = $("#div2-id").width();
clearTimeout(t);
}, delay);
The delay
is in milliseconds, so this assumes your CSS transition is 2s
.
回答3:
The transitionend Event
There is an event called transitionend. Adding a handler to this event will trigger any action after your transition ends instead of using a delay function
example click on the div box that has the text "left" inside.. when the transition ends the width of the div box that has the text "right" will pop up
function handler(){
if(window.getComputedStyle){
alert(window.getComputedStyle(document.getElementById('right'), 'width').width)
}
else {document.getElementById('right').currentStyle.width}
}
function click(){
document.getElementById('left').style.width='0px'
}
document.getElementById('left').addEventListener("transitionend",handler);
document.getElementById('left').addEventListener('click',click,false);
#left{
float:left;
transition-property:width;
transition-duration:3s;
border:solid;
width:100px;
}
#right{
border:solid;
overflow:hidden;
}
<div>
<div id="left">
left
</div>
<div id="right">
ddd
</div>
</div>
Note Beware
this event is only supported browser versions here http://www.w3schools.com/jsref/event_transitionend.asp
来源:https://stackoverflow.com/questions/34407186/how-to-detect-html-div-width-and-height-once-div-is-done-resizing