For example, it is possible to embed an image...
[Embed("myImage.png")]
public var myImage:Class;
and assign it to the mx:Image's source property like this :
<mx:Image source="{myImage}" />
but what if I want to be able to load the image from a compiled CSS file, something like:
.myImage {some-property: Embed("myImage.png"); }
What is the cleanest way to assign this kind of styled image to the mx:Image's source property ?
Alright, I found a solution:
You can load images in a component, spark Panel in this case :
s|Panel {
myImage: Embed(source="assets/images.swf", symbol="simple_image");
myOtherImage: Embed(source="assets/images.swf", symbol="other_image");
}
and then, when you change styles at runtime, you can react on StyleEvent.COMPLETE event:
var css:CSSStyleDeclaration = StyleManager.getStyleManager(null).getStyleDeclaration("spark.components.Panel");
var myImage:Object = css.getStyle("myImage");
var myOtherImage:Object = css.getStyle("myOtherImage");
From there you can easily assign those custom styled images to your mx:Image component's source.
Related
I am using Angular, my goal is to be able to use a string declared in typescript inside a CSS file. I am trying to set the background image of a navbar component. Later on, the background image path will be received from a database service, that's why I need it to be in the typescript file. I read something about using [ngStyle], but the img will not be updated, I just need the paths to be received from a database. Should I still try to use it? And how? I am a bit lost.
My typescript file has something like:
// ...
export class NavbarComponent{
background_url='../../../assets/img/background.png';
constructor() { }
// ...
And in my CSS file i want to do something like:
nav{
background-image: background_url;
}
However, this isn't working for me.
How could I better approach this? Thanks
I think it's not possible to access the ts file variables from the CSS file, but you can get elements from DOM and set style to that from the ts file.
an example:
document.getElementById('element').style.backgroundImage = background_url;
also if you are using frameworks like angular, you can use #ViewChild to get elements from DOM and style them by using the renderer2 library like this:
export class NavbarComponent {
#ViewChild('element') element: ElementRef;
background_url='../../../assets/img/background.png';
constructor(private renderer: Renderer2) {}
setStyle() {
this.renderer.setStyle(
this.element.nativeElement,
'background-image',
this.background_url
);
}
}
and then call the setStyle function where ever you want.
more from renderer2: https://angular.io/api/core/Renderer2
I would like to know how to apply CSS dynamically to all the elements in a page that belong to a CSS class in React JS?
Currently I am using the following:
document.querySelectorAll('.my-paragraph-class').forEach(function (x: any) {
x.style.fontSize = `${data.value}%`;
});
It works but I would like to know if there is a more efficient way instead of using document.querySelectorAll?
Also when the page loads new text, document.querySelectorAll has to be called again after the text loads, which is not ideal. I would like to know how to persist the modified CSS changes when new text is loaded dynamically?
Thank you in advance
For applying a static font size to a class you shouldn’t have to use JavaScript at all.
In your css file just do:
.my-paragraph-class: {
font-size: 10rem || whatever;
}
To dynamically add styling you could use a CSS in JS tool like styled components. For styled components you would import styled components and then write a code outside of your react function like this:
const StyledParagraph = styled.p`
font-size: 10rem || ${props => props.fontSize}
`
In your JSX you would do something like:
<StyledParagraph fontSize=“10rem”> Filler Text </StyledParagraph>
I am using primeface for the UI components and I have to set the background of the layout unit temporary its done by using the css style,
.layoutCustomStyle.ui-layout-unit-content
{
background-image: url('resources/images/backgrnd.png');
}
The id of the layoutunit is "layoutId" and the styleclass used is "layoutCustomStyle"
in xhtml,
<p:layoutUnit position="top" id= "layoutId" styleClass ="layoutCustomStyle">
</p:layoutUnit>
But what I want is to add the background image dynamically. The image will be chosen by file browser so, I cannot add a separate class for that and use bean.
UIViewRoot view = FacesContext.getCurrentInstance().getViewRoot();
UIComponent comp= view.findComponent("layoutId");
Map<String, Object> attrMap = comp.getAttributes();
String className = (String)attrMap.get("styleClass");
using this I can set and get class names but how to change the attribute "background-image:" dynamically?
Hope the question is clear.Any help appreciated.
Thanks in advance,
Pegasus
Use style attribute instead of styleClass.
This is an old question but at this time has been viewed 10,354 times. I want to share the way i resolve 'add a css style property dynamically' in primefaces 6.2
In my layout i have a header that i need change dyamically the image every 10|20 secs.
<h:panelGrid id="cabecera" columns="2" cellpadding="1" columnClasses="..."
style="width:100%; background-size: cover; background-position: center; background-image: url('#{request.contextPath}/resources/images/header/Vignette/#{userSelected.headerFile}');">
<h:form id="...." >
I have a list with the names of all the images that i can use and userSelected.headerFile choose one randomly.
Three similar options:
1.- At first i Use p:poll directly to update the panelGrid id 'cabecera':
<p:poll interval="10" update="#([id$=cabecera])" autoStart="true"/>
Of course that works, on every update the background image change. That could be enough in some cases where the update and page blink don´t be problem.
2.- Using a little of JavaScript, a bean method in the listener of p:poll.
Declare a js function to change the background property (or any other):
<script>
function headerBackground(urlBG) {
var laUrl = (urlBG);
document.getElementById('cabecera').style.backgroundImage = laUrl;
}
</script>
In my Bean userSelected i declared a method to call the javascript function via RequestContext.getCurrentInstance().execute(...). I decided received the url only and add the rest of values in the function:
public void callJSheaderBackground(String url) {
String jsFunc="headerBackground(\"".concat(url.trim()).concat("\")");
try{
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute(jsFunc);
}catch(Exception ex){
...
}
}
Finally the p:poll
<p:poll interval="20" listener="#{userSelected.callJSheaderBackground('url(\''.concat(request.contextPath).concat('/resources/images/header/Vignette/').concat(userSelected.headerFile).concat('\')'))}" autoStart="true"/>
3.- Calling directly a JS function
My JS function, reciving the contextPath and the image file name as parameters:
function setVignetteAsBackground(contextPath,vignetteName) {
var laUrl = "url('" + (contextPath)+'/resources/images/header/Vignette/'+(vignetteName)+"')";
document.getElementById('cabecera').style.backgroundImage = laUrl;
}
Then directly calling from p:poll on the onstart|oncomplete event:
<p:poll interval="20" onstart="setVignetteAsBackground('#{request.contextPath}','#{userSelected.headerFile}')" autoStart="true"/>
Hopefully be useful for somebody.
I have a Custom Component that has a couple of Canvas with some background colors assigned to them. Now i have hard coded the colors, i want to move them to an external css file.
So i would like to have the css declaration like this :
ControlBar
{
dividerRightColor: #ffffff;
dividerLeftColor: #f3f3f3;
}
My question is if i can define custom style names like dividerRightColor and if so, how can i use that value inside my MXML Component? I have seen examples of using them inside Pure AS components.
In CSS:
.dividerRightColor {
background-color: #ffffff;
}
.dividerLeftColor {
background-color: #f3f3f3;
}
In MXML:
<mx:ControlBar>
<mx:Canvas styleName="dividerLeftColor">
…
</mx:Canvas>
<mx:Canvas styleName="dividerRightColor">
…
</mx:Canvas>
</mx:ControlBar>
It sounds to me like you need to create the style in the component; not just send the style values into the component as the other answer.
Read this documentation.
Basically, styles don't get defined the same way that properties get defined. You can set any style name on the component you want. However, the component needs to know what to do w/ the style. To do that you need to override the styleChanged method:
override public function styleChanged(styleProp:String):void {
super.styleChanged(styleProp);
// Check to see if style changed.
if (styleProp=="dividerRightColor")
{
// do stuff to implement the style
dividerRight.setStyle('backgroundColor',getStyle('dividerRightColor'));
}
}
A common approach is to set "styleChanged" properties and invalidate the display list and then make the appropriate style changes in the updateDisplayList() method.
To make the style available in code hinting, you'll need to add metadata, like this:
[Style(name="dividerRightColor")]
This will only be required if you wish to set the style as a property in MXML.
I want to change the font characteristics for buttons in the toolbar of the RichTextEditor, but I want them to be different than other buttons in my application. Is there any way to do this with just CSS? I know that I can do it with setStyle if necessary...
One way to do it, since the RichTextEditor's sub-components are declared in MXML and are therefore publicly accessible, is to assign their styleName properties individually at runtime (after the container's creationComplete event fires, to be sure the editor and all its children have been created), like so:
<mx:Style>
.myRTECombo
{
color: #FF0000;
}
</mx:Style>
<mx:Script>
<![CDATA[
private function creationCompleteHandler(event:Event):void
{
rte.fontFamilyCombo.styleName = "myRTECombo";
rte.fontSizeCombo.styleName = "myRTECombo";
}
]]>
</mx:Script>
<mx:RichTextEditor id="rte" />
The Flex docs don't call out the subcomponents ("boldButton", "fontSizeCombo", et al) by ID, but the component's source is available for viewing, so you should be able to get all the info you need from the source code itself. Since I use FlexBuilder, I usually use the Eclipse Ctrl+click shortcut, on the tag/class name, to jump into the associated class-definition file, but you can also open the source file directly at [installDir]/sdks/[version]/frameworks/src/mx/RichTextEditor.mxml to have a look for yourself.
I'm sure there are other approaches (setStyle being one, although its explicit use is generally discouraged for performance reasons), but this ought to work out for you. One thing to note, though, as you'll see when you dig into the component's source, is that many of the buttons in the default button set actually use PNGs (e.g., icon_style_bold.png), not text, which is why my example includes a reference to the ComboBox instead, so you can see how the color changes apply; if you want to change the look of the buttons, be aware they're using the styleable icon property, not font-style settings, for their look and feel.
Hope it helps!
Thanks #Christian Nunciato! This is my final code, in my component that is a RichTextEditor (extends it). In the creationComplete, I call this
private function setUpStyleNames():void {
setUpStyleNamesInner(toolbar.getChildren());
setUpStyleNamesInner(toolBar2.getChildren());
}
private function setUpStyleNamesInner(children:Array):void {
for each (var child:DisplayObject in children) {
if (child is UIComponent) {
UIComponent(child).styleName = "rteInnards";
}
}
}
and then in my styleSheet, I have this
.rteInnards {
color: #FF0000;
fontSize: 25px;
}
Awesome. Thanks again!