2012-02-05 33 views
2

我使用GWT 2.3.0在我的项目的CSS。 我需要改变我的CSS源:在运行时(我想决定在onModuleLoad方法使用的文件)GWT注入运行时

。 什么是这样做的最佳笏?

回答

9

要注入的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;}"); 
+0

看起来我在这个问题上失败了两次(第一次提供错误的解决方案,第二次 - 忘记修复它)。感谢您发布正确的解决方案。 – jusio 2013-03-14 01:29:34

0

使用此方法JSNI并通过给URL的Y(路径调用此方法的形式onModuleLoad()GWT的我们的CSS)作为根据您的要求的论点。

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); 
}-*/;