GWT在运行时注入CSS

问题描述 投票:5回答:3

我在我的项目中使用gwt 2.3.0。我需要更改我的css源:

<link type="text/css" rel="stylesheet" href="gxt/css/gxt-all.css">

在运行时(我想决定在onModuleLoad方法上使用哪个文件)。这样做最好的是什么?

css gwt code-injection
3个回答
11
投票

要注入CSS文件,您需要以与ScriptInjector类似的方式继续javascript文件:

/** Load CSS file from url */
public static void loadCss(String url){
    LinkElement link = Document.get().createLinkElement();
    link.setRel("stylesheet");
    link.setHref(url);
    nativeAttachToHead(link);
}

/**
 * Attach element to head
 */
protected static native void nativeAttachToHead(JavaScriptObject scriptElement) /*-{
    $doc.getElementsByTagName("head")[0].appendChild(scriptElement);
}-*/;

@jusio:

StyleInjector.inject(...)仅适用于CSS内容:

StyleInjector.inject(".myClass{color:red;}");

1
投票

在GWT 2.8.2或J2CL上使用元素2:

 public static void loadCss(String url){
        HTMLDocument document = DomGlobal.document;

        Element link = document.createElement("link");
        link.setAttribute("rel", "stylesheet");
        link.setAttribute("type", "text/css");
        link.setAttribute("href", url);

        document.getElementsByTagName("head").getAt(0).appendChild(link);
    }

0
投票

使用此JSNI方法并通过根据您的要求将url(您的css的路径)作为参数来调用GWT的onModuleLoad()方法。

public static native void loadCss(String url)/*-{
    var fileref=document.createElement("link");
    fileref.setAttribute("rel","stylesheet");
    fileref.setAttribute("type","text/css");
    fileref.setAttribute("href",url);
    $doc.getElementsByTagName("head")[0].appendChild(fileref);
}-*/;
© www.soinside.com 2019 - 2024. All rights reserved.