How to make an image button in JSF

2019-04-03 06:58发布

I want to have a component that looks like a button, but instead of text it should contain an image. Because the standard button does not offer this functionality, I tried to use a <h:commandLink>:

<h:commandLink action="#{some_action}">
    <p:panel styleClass="some_style">
        <h:graphicImage value="#{some_image}">
    </p:panel>
</h:commandLink>

This doesn't work. The <h:commandLink> is translated into an <a> tag, and the <p:panel> into a <div>. <a>-tags may not contain <div>-tags, so the <div>-tag is automatically placed outside the <a>-tag. The result is that only the image is clickable, not the surrounding panel which is styled to look like a button. Is there a way to make the surrounding panel part of the link, or to put an image inside a button?

My project uses JSF and the Primefaces library:

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:composite="http://java.sun.com/jsf/composite"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.prime.com.tr/ui">

4条回答
乱世女痞
2楼-- · 2019-04-03 07:43

If the image does not fit then add properties to a сss class:

.button {
    background: white url('button.gif') no-repeat top;
    width: 32px;   // button width
    height: 32px;  // button height
    background-size: contain;
    border: none;  // hide border of button
}
查看更多
我命由我不由天
3楼-- · 2019-04-03 07:47

If you can use an icon from PrimeFaces/JSF, then there is a simple and sound solution is

<p:column>
    <p:commandButton icon="ui-icon-wrench"
     style="border-width:0;background:none;"/>
</p:column>

It may help to avoid JavaScript code in JSF.

查看更多
【Aperson】
4楼-- · 2019-04-03 07:53

There are a couple ways you can add an image to a commandButton:

Using the image attribute

<h:commandButton action="#{some_action}" image="button.gif" />

Absolute or relative URL of the image to be displayed for this button. If specified, this "input" element will be of type "image". Otherwise, it will be of the type specified by the "type" property with a label specified by the "value" property.

Use CSS

<h:commandButton action="#{some_action}" styleClass="button" />

.button {
    background: white url('button.gif') no-repeat top;
}
查看更多
Evening l夕情丶
5楼-- · 2019-04-03 07:55

You could just move the div outside e.g.

<div class="myButton">
<h:commandLink action="#{some_action}" styleClass="clickAll">
        <h:graphicImage value="#{some_image}">
</h:commandLink>
</div>

And style the div that way. Just make the anchor (a tag) display as a block and it should fill the whole div so it's all clickable. For example in your CSS go:

.clickAll{
  display:block;
}
查看更多
登录 后发表回答