无法将绝对css定位应用于我自己的复合按钮

时间:2013-03-19 20:42:01

标签: css gwt

这是我遇到的一个奇怪的问题,虽然我有一个解决方法,但我仍然想知道它为什么会发生。

这是我的复合类

    import com.google.gwt.event.dom.client.ClickEvent;
    import com.google.gwt.event.dom.client.ClickHandler;
    import com.google.gwt.event.dom.client.HasClickHandlers;
    import com.google.gwt.event.shared.HandlerRegistration;
    import com.google.gwt.user.client.ui.*;

    public class ExpandingOvalButton extends Composite implements HasClickHandlers
    {   
        private PushButton button;
        private Label label = new Label();
        private AbsolutePanel panel = new AbsolutePanel();

        public ExpandingOvalButton(String text)
        {       
            int width = 40;
            initWidget( panel );
            Image image = new Image( "icons/ovalBlueButton.png");
            label.setText(text);
            width = width + (text.length() * 8);
            String widthStr = width + "px";
            image.setWidth(widthStr);
            image.setHeight("50px");
            button = new PushButton( image );
            button.setWidth(widthStr);
            button.setHeight("50px");
            panel.setSize(widthStr, "50px");                
            panel.add(button, 0, 0);
            panel.add(label, 18, 14);
        }

        ...

当我将它与其他小部件一起添加到flex表格中时,它非常适合我,然后我可以将css样式应用于flextable并将其定位好。问题是,如果我想将css定位应用于ExpandingOvalButton实例,该实例不在其他面板内部,则它无法正常工作。

private ExpandingOvalButton startBtn = new ExpandingOvalButton("Start");
startBtn .getElement().setId("myId");


#myId
{
    position: absolute;
    left: 30%;
    top: 120px;
}

这不会使自己从左侧定位30%。 但是,如果我将startBtn添加到Panel然后将相同的CSS样式应用于Panel,它将自己从左侧定位30%。

panel.add(startBtn);
panel.getElement().setId("myId");

之前有人遇到过这个或知道可能导致它的原因吗?

1 个答案:

答案 0 :(得分:0)

如果你看一下AbsolutePanel的源代码,你会在构造函数中找到它:

DOM.setStyleAttribute(getElement(), "position", "relative");

这优先于你的css中声明的样式。您可以通过执行类似操作来强制它使用绝对定位:

DOM.setStyleAttribute(startBtn.getElement(), "position", "absolute");