我正在寻找一种在GWT中指定<g:SuggestBox>元素内的占位符属性的方法。我知道<input>元素允许指定该属性,但我决定切换到SuggestBox元素,而不是输入元素。
有谁可以帮我?
发布于 2012-02-16 23:48:37
您应该创建自己的自定义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,它有一个扩展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)构造函数。
发布于 2012-02-17 20:08:35
对SuggestBox进行子类化肯定是可行的。
如果您不想创建额外的类,也可以通过直接设置属性来轻松地将placeHolder添加到现有的SuggestBox中:
SuggestBox suggestBox = new SuggestBox();
suggestBox.getElement().setAttribute("placeHolder", "SOME TEXT);发布于 2013-12-18 04:49:56
请注意,如果在将小部件添加到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);
}
}
});https://stackoverflow.com/questions/9314132
复制相似问题