简体   繁体   中英

How to set styles using ExtJS

I wanted to change the styles like color, font size, background, etc of an element or extJS widget using following code but none works:

Ext.get('mydivid').setStyle({.......});     // does not work
Ext.get('mydivid').applyStyle({.......});   // does not work
Ext.select('mydivid').applyStyle({.......});   // does not work
Ext.query('.myclass').applyStyle({.......});   // does not work

And for extJs widget I tried using Ext.getCmp .

Does anyone know how to change the styles of an html element and extJS widget using extJS and not CSS?

Changing the style of HTML DOM elements is quite easy:

HTML

<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <div id="el1">Element 1</div>
        <div class="el">Element [1]</div>
        <div class="el">Element [2]</div>
    </body>
</html>

Javascript

Ext.onReady(function() {
    Ext.get('el1').setStyle('color', 'red');
    Ext.select('.el').setStyle('color', 'green');
});

Ext.query will not work directly as it returns a simple array of found DOM nodes, so you'd have to loop over the result to apply styles. What did you do exactly?

Styling widgets is not that easy unfortunately. Most widgets provide some styling attributes such as cls , ctCls , bodyCls or style but they are applied when rendering the component. To change the style of widgets after rendering you must change the widget's DOM elements directly using the methods above.

There is typo error in your question:

it is not applyStyle but applyStyles.

applyStyles is method of Ext.Element, you can use it as follows:

var win = new Ext.Window({
      width: 200, 
      height: 200
});
win.show();

win.body.applyStyles({ 
  'background-color':'red',
  'border': '1px solid blue'
});

The following is possible on the widget (but only before it is rendered, since the style config property is applied during render):

Ext.define('Ext.Component', {
  style: {},
  initComponent: function(config) {
    this.callParent(config);
    this.style['background-color'] = 'red';
  }
});

This is useful if say you are acting on some specific value of some other config setting.

As pointed out once rendered you have access to the setStyle() method of the encapsulated Ext.Element :

component.getEl().setStyle(config);

Finally you can go straight to the meat, and access the encapsulated DOM element directly:

component.getEl().dom.style.backgroundColor = 'red';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM