admin管理员组

文章数量:1296390

I'd like to know how to display alt text of img, inside of p element on mouse hover.

Here's my HTML:

<img src="img1.jpg" alt="one"/>
<img src="img2.jpg" alt="two"/>
<img src="img3.jpg" alt="three"/>

<p id="text"> </p>

And JS:

function showAlt(){
  var img = document.getElementsByTagName("img");
  var text = document.getElementById("text");

  for(var i=0; i < img.length; i++){
    img[i].addEventListener("mouseover", function(){
      var alt = img[i].alt;
      alt.appendChild(text);}}

}

And JSfiddle: here

I'd like to know how to display alt text of img, inside of p element on mouse hover.

Here's my HTML:

<img src="img1.jpg" alt="one"/>
<img src="img2.jpg" alt="two"/>
<img src="img3.jpg" alt="three"/>

<p id="text"> </p>

And JS:

function showAlt(){
  var img = document.getElementsByTagName("img");
  var text = document.getElementById("text");

  for(var i=0; i < img.length; i++){
    img[i].addEventListener("mouseover", function(){
      var alt = img[i].alt;
      alt.appendChild(text);}}

}

And JSfiddle: here

Share Improve this question asked May 2, 2016 at 22:43 MartinMartin 1433 gold badges6 silver badges13 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

I'm not sure of the context for this, but the title="" attribute is often shown as a tooltip for images. Should work in all of the desktop browsers, so I'm not sure if you need JS to do this.

You can change text of p element with textContent DEMO

var img = document.getElementsByTagName("img");
var text = document.getElementById("text");

for (var i = 0; i < img.length; i++) {
  img[i].addEventListener("mouseover", function() {
    var alt = this.alt;
    text.textContent = alt;
  });
}

If you want to remove text on mouseleave you can add another event and change text to empty string DEMO

本文标签: javascriptDisplay image Alt Attribute text on hoverStack Overflow