Change Image Source on Hover: A Comprehensive Guide
You may encounter a scenario where you need to dynamically change the source URL of an <img> tag when the mouse hovers over it. While it seems like a straightforward task, it's not as easily achievable as one might think.
The CSS Pitfall
Initially, you might try using CSS's content property to replace the image source, as seen in the following code:
#my-img:hover { content: url('http://dummyimage.com/100x100/eb00eb/fff'); }
However, this approach only works for Webkit browsers like Google Chrome. Other major browsers, such as Firefox and Safari, ignore the content property in this context.
The HTML and CSS Alternative
If CSS is not an option, you can consider replacing the <img> tag with a <div> tag. By setting the background image of the <div> and modifying it on hover, you can effectively achieve the desired result:
<div>
#my-div { background-image: url('http://dummyimage.com/100x100/000/fff'); } #my-div:hover { background-image: url('http://dummyimage.com/100x100/eb00eb/fff'); }
The JavaScript Solution
For the most versatility, you can leverage JavaScript to directly manipulate the src attribute of the <img> tag. This approach works across all major browsers:
<img>
const myImg = document.getElementById('my-img'); myImg.addEventListener('mouseover', () => { myImg.setAttribute('src', 'http://dummyimage.com/100x100/eb00eb/fff'); }); myImg.addEventListener('mouseout', () => { myImg.setAttribute('src', 'http://dummyimage.com/100x100/000/fff'); });
By employing one of these techniques, you can seamlessly change the source URL of an <img> tag on hover, providing dynamic and engaging visual experiences for your web applications.
The above is the detailed content of How Can I Change an Image Source on Hover?. For more information, please follow other related articles on the PHP Chinese website!