I'm using mootools 1.2 in a page where I'm loading a js graph into a div 开发者_StackOverflow中文版that is itself in a table cell. The graph loads properly, but it's quite a lot smaller than the width of the cell (the graph script is meant to generate a graph the same size as the div).
My question is: how can you set the size of the div based on the size of its parent container, dynamically (rather than setting a fixed pixel width of the div).
I'd like to set the size of the div with mootools setStyle on domready, like this (all wrapped in a domready
block):
var divwidth = $('my_chart').offsetParent.offsetWidth;
var divheight = $('my_chart').offsetParent.offsetHeight;
$('my_chart').setStyle('width', divwidth);
$('my_chart').setStyle('height', divheight);
g = new Dygraph($('my_chart'), data);
When I run the page without the setStyle stuff, it works, but the div returns a width of 480 when I execute $('my_chart').getStyle('width');
from a js console. However, the $('my_chart').offsetParent.offsetWidth
from the same console returns 1100.
The problem is that when I try to set the div size using the code above, it throws an error:
Uncaught TypeError: Cannot read property 'offsetWidth' of null
I assume because the div is not drawn yet?
Edit to add: if I set the width of the my_chart div to "auto", I get an error Uncaught TypeError: Cannot read property 'length' of undefined
from the graph script.
Thanks for any help.
http://jsfiddle.net/dimitar/c7GTA/
jsfiddle right back at you.
the problem is that this tool uses canvas. and it kind if needs to set the canvas width to a set value.
var c = document.id("mychart");
c.setStyle("width", c.getParent().getSize().x);
new Dygraph(document.id("mychart"),
"Date,Temperature\n" + "2008-05-07,75\n" + "2008-05-08,70\n" + "2008-05-09,80\n"
);
this works fine but table resize will make it look odd. use .getSize() which returns an object with x and y properties for width and height. don't trust computations based upon css/style.
精彩评论