【问题标题】:GWT SuggestBox with placeholder attribute具有占位符属性的 GWT SuggestBox
【发布时间】:2012-03-08 00:28:01
【问题描述】:

我正在寻找一种在 GWT 中指定 <g:SuggestBox> 元素内的占位符属性的方法。 我知道<input> 元素允许指定该属性,但我决定切换到 SuggestBox 元素而不是输入元素。

谁能帮帮我?

【问题讨论】:

标签: java google-app-engine gwt


【解决方案1】:

您应该创建自己的自定义 SuggestBox 小部件,之后您可以为其设置占位符属性。例如:

public class CustomSuggestBox extends SuggestBox {


 private String placeHolderText = "";

  public String getPlaceHolderText() {
   return placeHolderText;
  }

  public void setPlaceHolderText(String text) {
    placeHolderText = text;
    getTextBox().getElement().setAttribute("placeHolder", placeHolderText);
  }
}

因此,您可以在 UI 活页夹中设置此属性。

<widgets:CustomSuggestBox ui:field="cSuggestBox"  placeHolderText="someText" />

PS:它只适用于现代浏览器。为了在旧版浏览器上正确实现它,请查看第三方库 wogwt,它有 TextBoxWithPlaceholder 扩展 TextBox 的类:

 /**
 * A text box that displays a placeholder string when empty
 * 
 * <h3>CSS Style Rules</h3>
 * <ul class='css'>
 * <li>.wogwt-TextBoxWithPlaceholder { primary style }</li>
 * <li>.wogwt-TextBoxWithPlaceholder-placeholder { dependent style set when 
 * the placeholder is displayed }</li>
 * </ul>
 */  

在这种情况下,您可以将此TextBoxWithPlaceholder 的实例发送给SuggestBox(SuggestOracle oracle, TextBoxBase box) 构造函数。

【讨论】:

  • 我不确定这段代码 getTextBox().getElement().getStyle().setProperty("placeholder", placeHolderText);是正确的。我认为应该如下所述。
【解决方案2】:

请注意,如果您在将小部件添加到 DOM 之前调用 getElement() 方法,则会收到异常。因此,如果您想要一个允许您在将占位符文本添加到 DOM 之前设置占位符文本并在添加后显示的解决方案,您可以连接到 AttachEvent:

SuggestBox suggestBox = new SuggestBox();
// com.google.gwt.event.logical.shared.AttachEvent.Handler
suggestBox.addAttachHandler(new Handler() {
    @Override
    public void onAttachOrDetach(AttachEvent event) {
        if (event.isAttached()) {
            suggestBox.getElement().setAttribute("placeHolder", "SOME TEXT);
        }
    }
});

【讨论】:

    【解决方案3】:

    子类化 SuggestBox 肯定会起作用。
    如果您不想创建额外的类,您也可以通过直接设置属性轻松地将 placeHolder 添加到现有的SuggestBox:

    SuggestBox suggestBox = new SuggestBox();
    suggestBox.getElement().setAttribute("placeHolder", "SOME TEXT);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      • 2012-12-27
      相关资源
      最近更新 更多