请求修正代码:将HTML按钮替换为图片(JavaScript实现)
Got it, let's get this sorted for you! Instead of using a button, we'll swap it out for an image that triggers the same JavaScript function when clicked. Here's the revised, working code:
<!-- Clickable trigger image (replaces the button) --> <img src="your-clickable-image.png" alt="Click to update the target image" onclick="myFunction()" style="cursor: pointer;" > <!-- The target image that will be modified --> <img id="myImg" src="original-image.png" alt="Original display image"> <script> function myFunction() { // Update the source of the target image document.getElementById("myImg").src = "hackanm.gif"; } </script>
Key Changes & Explanations:
- Swapped the
<button>for an<img>tag: We added theonclick="myFunction()"attribute directly to this image, so clicking it fires the function exactly like the button did. - Added
cursor: pointerstyle: This gives users a clear visual cue that the image is interactive (the cursor changes to a hand icon when hovering). - Included
alttext for both images: This is critical for accessibility (screen readers rely on it) and acts as a fallback if images fail to load.
Quick Tips:
- Replace
"your-clickable-image.png"with the actual file path or URL of the image you want to use as the clickable trigger. - Double-check that your target image has the
id="myImg"attribute—this is how the JavaScript finds which element to update. - Make sure all image paths (including
hackanm.gif) are correct relative to your HTML file, or use full URLs if they're hosted externally.
内容的提问来源于stack exchange,提问作者Kenny Chan
相关产品推荐
相关产品推荐

