我正在寻找一种方法,在GWT中在
<g:SuggestBox>
元素内指定占位符属性。
我知道<input>
元素允许指定该属性,但我决定改用SuggestBox元素而不是输入元素。
有人能帮我吗?<g:SuggestBox>
元素内指定占位符属性。
我知道<input>
元素允许指定该属性,但我决定改用SuggestBox元素而不是输入元素。
有人能帮我吗?可以通过子类化SuggestBox
来实现功能。
如果您不想创建额外的类,也可以通过直接设置属性将placeHolder轻松添加到现有的SuggestBox
中:
SuggestBox suggestBox = new SuggestBox();
suggestBox.getElement().setAttribute("placeHolder", "SOME TEXT);
你应该创建自己的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);
}
}
<widgets:CustomSuggestBox ui:field="cSuggestBox" placeHolderText="someText" />
注意:此功能仅适用于现代浏览器。如果要在旧版浏览器中正确实现它,请查看第三方库wogwt,它具有扩展TextBox的TextBoxWithPlaceholder类:
/**
* 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)
构造函数。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);
}
}
});