简体   繁体   中英

How do i add an image to an element using javascript

I basically have this link, where when i click it, i want an image to show over it. Using javascript how can i do this?

<a> click me </a>

css:

a.clicked
{
   /*what goes here?*/
}

Adding a new image element is pretty easy:

// Append an image with source src to element
function appendImage(element, src, alt) {
  // DOM 0 method
  var image = new Image();

  // DOM 1+ - use this or above method
  // var image = document.createElement('img');

  // Set path and alt properties
  image.src = src;
  image.alt = alt;

  // Add it to the DOM
  element.appendChild(image);

  // If all went well, return false so navigation can 
  // be cancelled based on function outcome
  return false;
}

so in an A element:

<a onclick="appendImage(this, 'foo.jpg', 'Picture of foo');">Add an image</a>

If the A is a link and you wish to cancel navigation, return whatever the function returns. If the function doesn't return false, the link will be followed and should provide equivalent functionality:

<a href="link_to_picture or useful page" onclick="
  return appendImage(this, 'foo.jpg', 'Picture of foo');
">Add an image</a>

You should use like this. There are several other good methods, this is just for simplicity and understanding purpose

<body>
<a onClick='ChangeImage(this);return false'> Click Me <a>
</body>


<script>
function ChangeImage(obj)
{
 obj.innerHTML = "<img src='imangename.jpg'>";
}
</script>

The javascript plugin you may need is Highslides, Check here for examples.

Download highslides here .

First, you'll probably want to give the link an ID.

<a id="click-me">Click me!</a>

Then for the JavaScript..

document.getElementById('click-me').addEventListener('click', function () {
    var image = new Image();
    image.src = "your-picture.jpeg/png/whatever";
    this.appendChild(image);
});

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