从wicket面板类调用javascript或修改css

ily*_*tmn 0 java wicket panel wicketstuff

在我的项目中,我遇到了一个问题,从类中调用javascript代码
在wicket中呈现html.假设我们有一个类ExamplePanel,其中包含以下wicket面板代码

 public final class ExamplePanel extends Panel {

      public ExamplePanel(String id) {
          super(id);
          add(new Label("someText", "hello"));
      }}
Run Code Online (Sandbox Code Playgroud)

和html文件'ExamplePanel'

 <html xmlns:wicket>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>ExamplePanel</title>
        <wicket:head>
            <link href="panel.css" rel="stylesheet"/>
            <script src="jquery.min.js"></script>
            <script src="jquery-ui.min.js"></script>

        </wicket:head>
    </head>
    <body>
        <wicket:panel>
            <div id="parentContainer">
                <div id="box" wicket:id="someText"></div>
            </div>
        </wicket:panel>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

并遵循css

    #box{
    background: #f0f0f0;
    width: 50px;
    height: 50px;
    position: absolute;
    top: 200px;
    left: 200px;
    font-size: 1.5em;
    word-wrap: break-word; 
}

#parentContainer{
    width:500px;
    height: 500px;
     background:RGB(57,51,51);
     position:relative;
}
Run Code Online (Sandbox Code Playgroud)

从这段代码我们在parentContainer div中有框,我需要在初始化ExamplePanel类时将位置坐标传递给框,例如:

public ExamplePanel(String id) {
    super(id);
    add(new Label("someText", "hello"));
    // add some code for css positioning of box div
    // $('#div').css({position:'relative',top:'5px',left='29px'}) for example
}
Run Code Online (Sandbox Code Playgroud)

有什么建议?

小智 7

ExamplePanel必须实现IHeaderContributor,它提供方法renderHead(IHeaderResponse).从这个方法中,你可以调用response.renderString()传递你想要应用的样式.在您的情况下,您没有添加样式,您正在添加一个添加一些样式的JS调用.这样做会使java调用变得更简单,因为您不需要创建作为渲染字符串的一部分,而只需要调用response.renderJavascript()...

public class ExamplePanel implements IHeaderContributor {
    public ExamplePanel(String id) {
        super(id);

        add(new Label("someText", "hello"));
    }

    @Override
    public void renderHead(IHeaderResponse response) {
        // use this if you want to add only the styles
        response.renderString("<style>#div {position:'relative'; top:'5px'; left='29px';}</style>");

        // or, use this if you still want the JS selector
        // the uniqueId should not be null if you want Wicket to check if the script has already been rendered
        response.renderJavascript("$('#div').css({position:'relative',top:'5px',left='29px'})", null);
    }
}
Run Code Online (Sandbox Code Playgroud)

IHeaderContributor接口旨在促进添加JavaScript和CSS等资源.