问题
i am using the declarative/ui-binder method of adding images to a page. this is in combination with using the ImageBundle
functions that GWT provides.
what i would like to do is change the image out when i hover over the image. my questions are: what are the best way to do this, and is my current method the best method in the first place?
my code looks something similar to:
<ui:with field='res' type='path.to.my.app.AppResources' />
...
<g:HorizontalPanel ui:field='horizPanel' >
<g:Image ui:field='image1' resource='{res.image1}'/>
</g:HorizontalPanel>
that is then tied into an ImageBundle
class via the AbstractImagePrototype
.
then, in my main handler, i have something like:
@UiHandler("image1")
public void onMouseOver(MouseOverEvent event)
{
/* What do I do here? */
}
say i want to replace image1 with image2 when the user hovers over image1 (and put image1 back when the pointer leaves the image). do i replace the image1 object? do i use the setUrl function for that image? do i create a whole new image, and use the add/remove functions for the horizontal panel to add it on? that seems awfully inefficient. do i not even need an ImageBundle
; can i add images via something like <g:Image .... url='path/to/image1.png' />
and then use CSS and the hover attribute to swap out the image?
some guidance would be great. the GWT documentation is seriously lacking in this area. thanks.
回答1:
PushButton
is good for this kind of behavior. You can go father than :hover
- you can specify arbitrary html and widgets for different faces of the buttons.
See gwt pushButton in UiBinder for an example in uibinder.
There will be more overhead in this approach, since it does register mouse handlers and set up a whole widget - if you really only need the rollover image and not any other event handling, a :hover
css selector (maybe with a @sprite
?) is probably best.
回答2:
Using mouse handlers here seems a little overhead. I would use css and the hover selector
.foo {
background: url('path/to/image1.png');
/* height, width, etc. */
}
.foo:hover {
background: url('path/to/image2.png');
/* ... */
}
then use a widget that renders a div element (e.g. SimplePanel) instead of an image and set the style foo as stylePrimaryName
<g:HorizontalPanel ui:field='horizPanel' >
<g:SimplePanel ui:field='image1' stylePrimaryName='foo'/>
</g:HorizontalPanel>
来源:https://stackoverflow.com/questions/8302621/change-image-on-hover-using-gwt-and-ui-binder