简体   繁体   中英

How to make images appear in Javascript

I'm not very fluent in javascript, and I feel like this is really basic, but I can't seem to find it online anywhere .

I want to create a link that will trigger a javascript function that makes an image appear in a separate div. It can't be in flash, otherwise I have no objection to the coding language.

I have several images, so I would think that the best way to do this would be to layer them all on top of each other and then increase the z-index each time their link is clicked, but you might have a better idea.

I really just want someway to create a sort of primitive image gallery that doesn't use flash and displays the photo in its div when the corresponding link is clicked.

Thanks in advance, Alex

As Jessegavin said (found here )

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
  var img = document.createElement("img");
  img.src = src;
  img.width = width;
  img.height = height;
  img.alt = alt;
  
  // This next line will just add it to the <body> tag
  document.body.appendChild(img); 
}

Then you could use it like this...

<button onclick="show_image('http://google.com/images/logo.gif', 
  276,110, 'Google Logo");'>Add Google Logo</button> 

There shouldn't be a line break above, I added it so that it could show without scrolling See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

This should answer your question

There are a ton of javascript libraries, plugins (for jQuery) and other ways of solving this problem.

First thing I would do is to peruse a website like this, to see what's available: http://sixrevisions.com/javascript/free_javascript_image_galleries/

I have used this one before, and it's pretty straight forward: http://lokeshdhakar.com/projects/lightbox2/

In general though you can just do <a href="javascript: showImage()">Link</a> and clicking that will call the javascript function showImage() that you define somewhere. Then layering the divs will work as you have described.

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