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