Change the image of a JSF commandbutton with DHTML event onmouseover

烂漫一生 提交于 2019-12-21 17:49:29

问题


I want to change the image of my button when the mouse goes over it.

I rode the DHTML event onmouseover, can do that for me, but how?

Do i need to create a javascript also for it?

What should i do to make it work?

This is my current code:

<h:commandButton class="btn" image="/resources/images/mainbtn1.png" onmouseover="/resources/images/mainbtn2.png"/">

回答1:


The <h:commandButton image="foo.png"> generates a HTML <input type="image" src="foo.png">. The onmouseover attribute (like as all on* attributes) should point to JavaScript functions. However, you're putting the image path plain there. This would only result in a JavaScript error (which you would have noticed if you were using Firebug or WDT).

You need to write some JS which changes the src attribute of the image button accordingly:

onmouseover="this.src='/resources/images/mainbtn2.png'"

Don't forget to add an onmouseout which changes the image back.


Unrelated to the concrete problem, the normal practice is to use CSS background images for this. The HTML <input type="image"> has technically an entirely different purpose. It represents namely an image map which allows you to send the mouse coordinates of where you have clicked in the image map. You're apparently not interested in this information as you're not using a static image.

E.g.

<h:commandButton value="" styleClass="mybutton" />

which generates

<input type="submit" value="" class="mybutton" />

and add this CSS (kickoff example)

.mybutton {
    margin: 2px;
    padding: 0;
    border: 0;
    width: 100px;
    height: 20px;
    background-image: url('foo.png');
    cursor: pointer;
    overflow: visible;
}

.mybutton:hover {
    background-image: url('bar.png');
}

This is not only better reuseable/maintainable, but also doesn't require JS support.




回答2:


Yes, all onXXX attributes are for JavaScript event handlers. You need to have a JavaScript function written for that. Something like this:

function changeImage() {
    this.style.backgroundImage = "url('path/to/image.png')";
}

And invoked using:

<h:commandButton class="btn" image="/resources/images/mainbtn1.png" onmouseover="changeImage()" />

Note: I can't provide you the exact JavaScript as it entirely depends on how the markup is generated by the JSF library that you're using.



来源:https://stackoverflow.com/questions/7285613/change-the-image-of-a-jsf-commandbutton-with-dhtml-event-onmouseover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!