Upgrade to ExtJS 3.0.0 - Released 07/06/2009
[extjs.git] / src / core / core / Element.style.js
1 /*!
2  * Ext JS Library 3.0.0
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**\r
8  * @class Ext.Element\r
9  */\r
10 Ext.Element.addMethods(function(){  \r
11     // local style camelizing for speed\r
12     var propCache = {},\r
13         camelRe = /(-[a-z])/gi,\r
14         classReCache = {},\r
15         view = document.defaultView,\r
16         propFloat = Ext.isIE ? 'styleFloat' : 'cssFloat',\r
17         opacityRe = /alpha\(opacity=(.*)\)/i,\r
18         trimRe = /^\s+|\s+$/g,\r
19         EL = Ext.Element,   \r
20         PADDING = "padding",\r
21         MARGIN = "margin",\r
22         BORDER = "border",\r
23         LEFT = "-left",\r
24         RIGHT = "-right",\r
25         TOP = "-top",\r
26         BOTTOM = "-bottom",\r
27         WIDTH = "-width",    \r
28         MATH = Math,\r
29         HIDDEN = 'hidden',\r
30         ISCLIPPED = 'isClipped',\r
31         OVERFLOW = 'overflow',\r
32         OVERFLOWX = 'overflow-x',\r
33         OVERFLOWY = 'overflow-y',\r
34         ORIGINALCLIP = 'originalClip',\r
35         // special markup used throughout Ext when box wrapping elements    \r
36         borders = {l: BORDER + LEFT + WIDTH, r: BORDER + RIGHT + WIDTH, t: BORDER + TOP + WIDTH, b: BORDER + BOTTOM + WIDTH},\r
37         paddings = {l: PADDING + LEFT, r: PADDING + RIGHT, t: PADDING + TOP, b: PADDING + BOTTOM},\r
38         margins = {l: MARGIN + LEFT, r: MARGIN + RIGHT, t: MARGIN + TOP, b: MARGIN + BOTTOM},\r
39         data = Ext.Element.data;\r
40         \r
41     \r
42     // private  \r
43     function camelFn(m, a) {\r
44         return a.charAt(1).toUpperCase();\r
45     }\r
46     \r
47     // private (needs to be called => addStyles.call(this, sides, styles))\r
48     function addStyles(sides, styles){\r
49         var val = 0;    \r
50         \r
51         Ext.each(sides.match(/\w/g), function(s) {\r
52             if (s = parseInt(this.getStyle(styles[s]), 10)) {\r
53                 val += MATH.abs(s);      \r
54             }\r
55         },\r
56         this);\r
57         return val;\r
58     }\r
59 \r
60     function chkCache(prop) {\r
61         return propCache[prop] || (propCache[prop] = prop == 'float' ? propFloat : prop.replace(camelRe, camelFn));\r
62 \r
63     }\r
64             \r
65     return {    \r
66         // private  ==> used by Fx  \r
67         adjustWidth : function(width) {\r
68             var me = this;\r
69             var isNum = (typeof width == "number");\r
70             if(isNum && me.autoBoxAdjust && !me.isBorderBox()){\r
71                width -= (me.getBorderWidth("lr") + me.getPadding("lr"));\r
72             }\r
73             return (isNum && width < 0) ? 0 : width;\r
74         },\r
75         \r
76         // private   ==> used by Fx \r
77         adjustHeight : function(height) {\r
78             var me = this;\r
79             var isNum = (typeof height == "number");\r
80             if(isNum && me.autoBoxAdjust && !me.isBorderBox()){\r
81                height -= (me.getBorderWidth("tb") + me.getPadding("tb"));               \r
82             }\r
83             return (isNum && height < 0) ? 0 : height;\r
84         },\r
85     \r
86     \r
87         /**\r
88          * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.\r
89          * @param {String/Array} className The CSS class to add, or an array of classes\r
90          * @return {Ext.Element} this\r
91          */\r
92         addClass : function(className){\r
93             var me = this;\r
94             Ext.each(className, function(v) {\r
95                 me.dom.className += (!me.hasClass(v) && v ? " " + v : "");  \r
96             });\r
97             return me;\r
98         },\r
99     \r
100         /**\r
101          * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.\r
102          * @param {String/Array} className The CSS class to add, or an array of classes\r
103          * @return {Ext.Element} this\r
104          */\r
105         radioClass : function(className){\r
106             Ext.each(this.dom.parentNode.childNodes, function(v) {\r
107                 if(v.nodeType == 1) {\r
108                     Ext.fly(v, '_internal').removeClass(className);          \r
109                 }\r
110             });\r
111             return this.addClass(className);\r
112         },\r
113     \r
114         /**\r
115          * Removes one or more CSS classes from the element.\r
116          * @param {String/Array} className The CSS class to remove, or an array of classes\r
117          * @return {Ext.Element} this\r
118          */\r
119         removeClass : function(className){\r
120             var me = this;\r
121             if (me.dom.className) {\r
122                 Ext.each(className, function(v) {               \r
123                     me.dom.className = me.dom.className.replace(\r
124                         classReCache[v] = classReCache[v] || new RegExp('(?:^|\\s+)' + v + '(?:\\s+|$)', "g"), \r
125                         " ");               \r
126                 });    \r
127             }\r
128             return me;\r
129         },\r
130     \r
131         /**\r
132          * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).\r
133          * @param {String} className The CSS class to toggle\r
134          * @return {Ext.Element} this\r
135          */\r
136         toggleClass : function(className){\r
137             return this.hasClass(className) ? this.removeClass(className) : this.addClass(className);\r
138         },\r
139     \r
140         /**\r
141          * Checks if the specified CSS class exists on this element's DOM node.\r
142          * @param {String} className The CSS class to check for\r
143          * @return {Boolean} True if the class exists, else false\r
144          */\r
145         hasClass : function(className){\r
146             return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;\r
147         },\r
148     \r
149         /**\r
150          * Replaces a CSS class on the element with another.  If the old name does not exist, the new name will simply be added.\r
151          * @param {String} oldClassName The CSS class to replace\r
152          * @param {String} newClassName The replacement CSS class\r
153          * @return {Ext.Element} this\r
154          */\r
155         replaceClass : function(oldClassName, newClassName){\r
156             return this.removeClass(oldClassName).addClass(newClassName);\r
157         },\r
158         \r
159         isStyle : function(style, val) {\r
160             return this.getStyle(style) == val;  \r
161         },\r
162     \r
163         /**\r
164          * Normalizes currentStyle and computedStyle.\r
165          * @param {String} property The style property whose value is returned.\r
166          * @return {String} The current value of the style property for this element.\r
167          */\r
168         getStyle : function(){         \r
169             return view && view.getComputedStyle ?\r
170                 function(prop){\r
171                     var el = this.dom,\r
172                         v,                  \r
173                         cs;\r
174                     if(el == document) return null;\r
175                     prop = chkCache(prop);\r
176                     return (v = el.style[prop]) ? v : \r
177                            (cs = view.getComputedStyle(el, "")) ? cs[prop] : null;\r
178                 } :\r
179                 function(prop){      \r
180                     var el = this.dom, \r
181                         m, \r
182                         cs;     \r
183                         \r
184                     if(el == document) return null;      \r
185                     if (prop == 'opacity') {\r
186                         if (el.style.filter.match) {                       \r
187                             if(m = el.style.filter.match(opacityRe)){\r
188                                 var fv = parseFloat(m[1]);\r
189                                 if(!isNaN(fv)){\r
190                                     return fv ? fv / 100 : 0;\r
191                                 }\r
192                             }\r
193                         }\r
194                         return 1;\r
195                     }\r
196                     prop = chkCache(prop);  \r
197                     return el.style[prop] || ((cs = el.currentStyle) ? cs[prop] : null);\r
198                 };\r
199         }(),\r
200         \r
201         /**\r
202          * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values\r
203          * are convert to standard 6 digit hex color.\r
204          * @param {String} attr The css attribute\r
205          * @param {String} defaultValue The default value to use when a valid color isn't found\r
206          * @param {String} prefix (optional) defaults to #. Use an empty string when working with\r
207          * color anims.\r
208          */\r
209         getColor : function(attr, defaultValue, prefix){\r
210             var v = this.getStyle(attr),\r
211                 color = prefix || '#',\r
212                 h;\r
213                 \r
214             if(!v || /transparent|inherit/.test(v)){\r
215                 return defaultValue;\r
216             }\r
217             if(/^r/.test(v)){\r
218                 Ext.each(v.slice(4, v.length -1).split(','), function(s){\r
219                     h = parseInt(s, 10);\r
220                     color += (h < 16 ? '0' : '') + h.toString(16); \r
221                 });\r
222             }else{\r
223                 v = v.replace('#', '');\r
224                 color += v.length == 3 ? v.replace(/^(\w)(\w)(\w)$/, '$1$1$2$2$3$3') : v;\r
225             }\r
226             return(color.length > 5 ? color.toLowerCase() : defaultValue);\r
227         },\r
228     \r
229         /**\r
230          * Wrapper for setting style properties, also takes single object parameter of multiple styles.\r
231          * @param {String/Object} property The style property to be set, or an object of multiple styles.\r
232          * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.\r
233          * @return {Ext.Element} this\r
234          */\r
235         setStyle : function(prop, value){\r
236             var tmp, \r
237                 style,\r
238                 camel;\r
239             if (!Ext.isObject(prop)) {\r
240                 tmp = {};\r
241                 tmp[prop] = value;          \r
242                 prop = tmp;\r
243             }\r
244             for (style in prop) {\r
245                 value = prop[style];            \r
246                 style == 'opacity' ? \r
247                     this.setOpacity(value) : \r
248                     this.dom.style[chkCache(style)] = value;\r
249             }\r
250             return this;\r
251         },\r
252         \r
253         /**\r
254          * Set the opacity of the element\r
255          * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc\r
256          * @param {Boolean/Object} animate (optional) a standard Element animation config object or <tt>true</tt> for\r
257          * the default animation (<tt>{duration: .35, easing: 'easeIn'}</tt>)\r
258          * @return {Ext.Element} this\r
259          */\r
260          setOpacity : function(opacity, animate){\r
261             var me = this,\r
262                 s = me.dom.style;\r
263                 \r
264             if(!animate || !me.anim){            \r
265                 if(Ext.isIE){\r
266                     var opac = opacity < 1 ? 'alpha(opacity=' + opacity * 100 + ')' : '', \r
267                     val = s.filter.replace(opacityRe, '').replace(trimRe, '');\r
268 \r
269                     s.zoom = 1;\r
270                     s.filter = val + (val.length > 0 ? ' ' : '') + opac;\r
271                 }else{\r
272                     s.opacity = opacity;\r
273                 }\r
274             }else{\r
275                 me.anim({opacity: {to: opacity}}, me.preanim(arguments, 1), null, .35, 'easeIn');\r
276             }\r
277             return me;\r
278         },\r
279         \r
280         /**\r
281          * Clears any opacity settings from this element. Required in some cases for IE.\r
282          * @return {Ext.Element} this\r
283          */\r
284         clearOpacity : function(){\r
285             var style = this.dom.style;\r
286             if(Ext.isIE){\r
287                 if(!Ext.isEmpty(style.filter)){\r
288                     style.filter = style.filter.replace(opacityRe, '').replace(trimRe, '');\r
289                 }\r
290             }else{\r
291                 style.opacity = style['-moz-opacity'] = style['-khtml-opacity'] = '';\r
292             }\r
293             return this;\r
294         },\r
295     \r
296         /**\r
297          * Returns the offset height of the element\r
298          * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding\r
299          * @return {Number} The element's height\r
300          */\r
301         getHeight : function(contentHeight){\r
302             var me = this,\r
303                 dom = me.dom,\r
304                 h = MATH.max(dom.offsetHeight, dom.clientHeight) || 0;\r
305             h = !contentHeight ? h : h - me.getBorderWidth("tb") - me.getPadding("tb");\r
306             return h < 0 ? 0 : h;\r
307         },\r
308     \r
309         /**\r
310          * Returns the offset width of the element\r
311          * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding\r
312          * @return {Number} The element's width\r
313          */\r
314         getWidth : function(contentWidth){\r
315             var me = this,\r
316                 dom = me.dom,\r
317                 w = MATH.max(dom.offsetWidth, dom.clientWidth) || 0;\r
318             w = !contentWidth ? w : w - me.getBorderWidth("lr") - me.getPadding("lr");\r
319             return w < 0 ? 0 : w;\r
320         },\r
321     \r
322         /**\r
323          * Set the width of this Element.\r
324          * @param {Mixed} width The new width. This may be one of:<div class="mdetail-params"><ul>\r
325          * <li>A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).</li>\r
326          * <li>A String used to set the CSS width style. Animation may <b>not</b> be used.\r
327          * </ul></div>\r
328          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object\r
329          * @return {Ext.Element} this\r
330          */\r
331         setWidth : function(width, animate){\r
332             var me = this;\r
333             width = me.adjustWidth(width);\r
334             !animate || !me.anim ? \r
335                 me.dom.style.width = me.addUnits(width) :\r
336                 me.anim({width : {to : width}}, me.preanim(arguments, 1));\r
337             return me;\r
338         },\r
339     \r
340         /**\r
341          * Set the height of this Element.\r
342          * <pre><code>\r
343 // change the height to 200px and animate with default configuration\r
344 Ext.fly('elementId').setHeight(200, true);\r
345 \r
346 // change the height to 150px and animate with a custom configuration\r
347 Ext.fly('elId').setHeight(150, {\r
348     duration : .5, // animation will have a duration of .5 seconds\r
349     // will change the content to "finished"\r
350     callback: function(){ this.{@link #update}("finished"); } \r
351 });\r
352          * </code></pre>\r
353          * @param {Mixed} height The new height. This may be one of:<div class="mdetail-params"><ul>\r
354          * <li>A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels.)</li>\r
355          * <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>\r
356          * </ul></div>\r
357          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object\r
358          * @return {Ext.Element} this\r
359          */\r
360          setHeight : function(height, animate){\r
361             var me = this;\r
362             height = me.adjustHeight(height);\r
363             !animate || !me.anim ? \r
364                 me.dom.style.height = me.addUnits(height) :\r
365                 me.anim({height : {to : height}}, me.preanim(arguments, 1));\r
366             return me;\r
367         },\r
368         \r
369         /**\r
370          * Gets the width of the border(s) for the specified side(s)\r
371          * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,\r
372          * passing <tt>'lr'</tt> would get the border <b><u>l</u></b>eft width + the border <b><u>r</u></b>ight width.\r
373          * @return {Number} The width of the sides passed added together\r
374          */\r
375         getBorderWidth : function(side){\r
376             return addStyles.call(this, side, borders);\r
377         },\r
378     \r
379         /**\r
380          * Gets the width of the padding(s) for the specified side(s)\r
381          * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,\r
382          * passing <tt>'lr'</tt> would get the padding <b><u>l</u></b>eft + the padding <b><u>r</u></b>ight.\r
383          * @return {Number} The padding of the sides passed added together\r
384          */\r
385         getPadding : function(side){\r
386             return addStyles.call(this, side, paddings);\r
387         },\r
388     \r
389         /**\r
390          *  Store the current overflow setting and clip overflow on the element - use <tt>{@link #unclip}</tt> to remove\r
391          * @return {Ext.Element} this\r
392          */\r
393         clip : function(){\r
394             var me = this,\r
395                 dom = me.dom;\r
396                 \r
397             if(!data(dom, ISCLIPPED)){\r
398                 data(dom, ISCLIPPED, true);\r
399                 data(dom, ORIGINALCLIP, {\r
400                     o: me.getStyle(OVERFLOW),\r
401                     x: me.getStyle(OVERFLOWX),\r
402                     y: me.getStyle(OVERFLOWY)\r
403                 });\r
404                 me.setStyle(OVERFLOW, HIDDEN);\r
405                 me.setStyle(OVERFLOWX, HIDDEN);\r
406                 me.setStyle(OVERFLOWY, HIDDEN);\r
407             }\r
408             return me;\r
409         },\r
410     \r
411         /**\r
412          *  Return clipping (overflow) to original clipping before <tt>{@link #clip}</tt> was called\r
413          * @return {Ext.Element} this\r
414          */\r
415         unclip : function(){\r
416             var me = this,\r
417                 dom = me.dom;\r
418                 \r
419             if(data(dom, ISCLIPPED)){\r
420                 data(dom, ISCLIPPED, false);\r
421                 var o = data(dom, ORIGINALCLIP);\r
422                 if(o.o){\r
423                     me.setStyle(OVERFLOW, o.o);\r
424                 }\r
425                 if(o.x){\r
426                     me.setStyle(OVERFLOWX, o.x);\r
427                 }\r
428                 if(o.y){\r
429                     me.setStyle(OVERFLOWY, o.y);\r
430                 }\r
431             }\r
432             return me;\r
433         },\r
434         \r
435         addStyles : addStyles,\r
436         margins : margins\r
437     }\r
438 }()         \r
439 );