开发者

How do i add an image to an element using javascript

开发者 https://www.devze.com 2023-03-08 16:16 出处:网络
I basically have thi开发者_Python百科s link, where when i click it, i want an image to show over it.Using javascript how can i do this?

I basically have thi开发者_Python百科s 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);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消