简体   繁体   中英

Change Image Source from Div with onmouseover

Is it possible to change the image source from the containing div? The images are dynamic and pulled from the database.

v = $"<div onmouseover=\"document.navIcon.src='/Images/White/{reader[2]}';\" 
      onmouseout=\"document.navIcon.src='/Images/{reader[2]}';\">
<img name=\"navIcon\" src=\"Images/{reader[2]}\"><br>{reader[1]}</div>";

That was my thoughts on how to do it but it doesn't appear to work as expected. I was able to get it to work when I put the onmouseover portion in the < img > however, I want it to change anywhere in the div, like over the reader[1] text, not just directly over the image.

Thoughts?

The best way to accomplish that is to use CSS.

HTML

<img id="NavIcon">

CSS

#Navicon {
  background-image: url(image1.jpg);
}
#NavIcon:hover {
  background-image: url(image2.jpg);
}

I just grabbed some images off google images. You can use this to refer to the current element.

 <img src='https://osu.ppy.sh/forum/images/smilies/50.gif' onmouseover='this.src="http://4.bp.blogspot.com/-YrmTHhfMtFU/VJNbpDMHzgI/AAAAAAAAH8c/g3dJ1Q-QTrc/s1600/smile.png"' onmouseout='this.src="https://osu.ppy.sh/forum/images/smilies/50.gif"' /> 


Edit..

This will change the image when you hover on anything with a "hoverme" class name.

 (function() { var img1 = "https://osu.ppy.sh/forum/images/smilies/50.gif"; var img2 = "http://4.bp.blogspot.com/-YrmTHhfMtFU/VJNbpDMHzgI/AAAAAAAAH8c/g3dJ1Q-QTrc/s1600/smile.png"; var myimg = document.getElementById('myimg'); myimg.src = img1; var hoverables = document.getElementsByClassName('hoverme'); for (var i = hoverables.length; i--;) { hoverables[i].addEventListener("mouseover", hoverMe, false); hoverables[i].addEventListener("mouseout", unhoverMe, false); } function hoverMe() { myimg.src = img2; } function unhoverMe() { myimg.src = img1; } })(); 
 <img class='hoverme' id='myimg' /> <p class='hoverme'>poooooooop</p> <div class='hoverme'>This si a diiiiivvvvv</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM