Creating custom graphic buttons using HTML and JavaScript is surprisingly straightforward! This tutorial demonstrates how to build a button with three distinct states (up, over, down) using image swapping.
We'll use three images: ButtonSubmit.gif
(default), ButtonSubmit-over.gif
(mouse over), and ButtonSubmit-down.gif
(mouse click).
Here's the code:
<a href="//m.sbmmt.com/link/93ac0c50dd620dc7b88e5fe05c70e15b" onmouseover="ReplaceImage('ImgSubmit', 'ButtonSubmit-over.gif')" onmousedown="ReplaceImage('ImgSubmit', 'ButtonSubmit-down.gif')" onmouseout="ReplaceImage('ImgSubmit', 'ButtonSubmit.gif')"> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174136519147164.gif" class="lazy" alt="Simulate a Windows-like Button Using JavaScript "> </a>
The ReplaceImage()
JavaScript function takes the image's name and the new file path as arguments, dynamically updating the image source. The <a></a>
tag's event handlers (onmouseover
, onmousedown
, onmouseout
) trigger the image swap based on user interaction. The image itself is nested within the <a></a>
tag. Note the addition of an alt
attribute for accessibility.
Explanation:
ReplaceImage(sImgName, sImgFile)
: This function updates the src
attribute of the image element identified by sImgName
with the new image path sImgFile
.
<a href="//m.sbmmt.com/link/93ac0c50dd620dc7b88e5fe05c70e15b"></a>
: This creates a hyperlink; the href="//m.sbmmt.com/link/93ac0c50dd620dc7b88e5fe05c70e15b"
prevents navigation to a new page.
onmouseover
, onmousedown
, onmouseout
: These event attributes call ReplaceImage()
to change the image based on the mouse's state (hover, click, leave).
<img ... alt="Simulate a Windows-like Button Using JavaScript" >
: This displays the image, with name="ImgSubmit"
allowing JavaScript to reference it.
This approach creates a visually appealing button with dynamic image changes, mimicking the look and feel of buttons in many applications. Remember to replace "ButtonSubmit.gif"
, "ButtonSubmit-over.gif"
, and "ButtonSubmit-down.gif"
with the actual paths to your image files. For best results, use images of consistent size to prevent layout shifts.
The above is the detailed content of Simulate a Windows-like Button Using JavaScript. For more information, please follow other related articles on the PHP Chinese website!