简体   繁体   中英

How do I create a function to change my paragraph into an img with an onmouseover

< p id="p1" onmouseover="this.style.color='transparent';flipPara()">
< p id="p2" onmouseover="spookyPara()">

function spookyPara() {
  document.getElementById("p1").attribute = "All_Images/ghost.png";
}

This is (parts of) the code I currently have. I've run it through a validator and it says it is good, but when I mouse over the second paragraph it doesn't change the first paragraph into the image I would like.

You could use innerhtml to replace the paragraph tag with the image tag on mouseover. On the mouse over event call you could call the below code:

document.getElementById("para").innerHTML = "<img src='url'/>";

This is the jsfiddle link

Easiest way is to put a paragraph and an image alongside one another in a div and track the mouse hover on the div, then use css to hide/show it like so:

HTML

<div id="spookyPara">
  <p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
  </p>
  <img class="hide" src="https://placehold.it/200x200"/>
</div>

CSS

#spookyPara{
  width: 200px;
  height: 200px;
}
.hide{
  display: none;
}
#spookyPara:hover p{
  display: none;
}
#spookyPara:hover img{
  display: block;
}

If you were determined to go down the js route, you could try something like this (I'd recommend the css solution though):

<div id="spookyPara" onmouseover="spookyPara()" onmouseout="unspookyPara()">

JS

function spookyPara(){
    document.querySelector("#spookyPara > p").classList.add('hide');
    document.querySelector("#spookyPara > img").classList.remove('hide');
}
function unspookyPara(){
    document.querySelector("#spookyPara > p").classList.remove('hide');
    document.querySelector("#spookyPara > img").classList.add('hide');
}

JSFiddle: https://jsfiddle.net/hyhmkv02/

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