Modifying Image Source on Hover Using HTML, CSS, and JavaScript
To modify the source URL of an <img> tag upon hovering, various approaches can be taken.
CSS-Only (Webkit-Specific)
Using CSS alone, you can replace the image with a different URL on hover. However, it only works in Webkit-based browsers like Google Chrome:
#my-img:hover { content: url('http://dummyimage.com/100x100/eb00eb/fff'); }
Using a Div Background Image
Alternatively, you can use a
div { background: url('http://dummyimage.com/100x100/000/fff'); } div:hover { background: url('http://dummyimage.com/100x100/eb00eb/fff'); }
Using JavaScript
With JavaScript, you can dynamically set the source of the <img> tag on mouseover and mouseout:
function hover(element) { element.setAttribute('src', 'http://dummyimage.com/100x100/eb00eb/fff'); } function unhover(element) { element.setAttribute('src', 'http://dummyimage.com/100x100/000/fff'); }
<img>
The above is the detailed content of How Can I Change an Image Source on Hover Using HTML, CSS, and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!