简体   繁体   中英

How to enlarge an image in a new window using Javascript

I've seen plenty of solutions for this using jQuery but I need to do it in Javascript only. I'm trying to write a script that will attach an onclick listener to every image on a page, with a function that opens the clicked image in a new window at double its width & height. The problems I'm having are that the new window opens when the page loads, not when the image is clicked, and the new window is showing "undefined" for the image source and "NaN" for its width and height. Here is my .js:

var x = document.images;
var imageWindow;

function magnify() {
   for (var i = 0; i < x.length; i++) {
     x[i].addEventListener('click', launchWindow(this), false);
   }
}

function launchWindow(img) {
   var h = img.height * 2.0;
   var w = img.width * 2.0;
   imageWindow = window.open();
   imageWindow.document.write("<html><head><title>Image</title></head><body><img src=" + img.src + " width=" + w + " height=" + h + " alt='Magnified image'></body></html>");

   if(window.focus) {
     imageWindow.focus;
   }
}

And the relevant HTML of my test page:

Your loop to assign the event handler is actually running the event handler rather than assigning it. Try doing this instead:

x[i].addEventListener('click', function() { launchWindow(this) }, false);

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