简体   繁体   English

如何使用一个Javascript函数将数组中多张图片的大小加倍

[英]How to double the size of multiple pictures in an array with one Javascript function

I have an array that contains 5 images. 我有一个包含5张图片的数组。 When I mouseover the images I want them to double in size and then return to original size onmouseout. 当我将鼠标悬停在图片上时,我希望它们的尺寸加倍,然后在鼠标移出时恢复为原始尺寸。 I know how to do this by coding each image individually but I was wondering if there was a way to write one Javascript function (please only Javascript, I'm not allowed to use JQuery for this assignment) that will affect all the images? 我知道如何通过分别编码每个图像来做到这一点,但是我想知道是否有一种方法可以影响所有图像(仅Javascript,不允许我使用JQuery进行此分配)。 Here is what I have so far: 这是我到目前为止的内容:

My array: 我的数组:

var myImages = new Array("usa.png", "canada.png", "jamaica.png", "mexico.png", "pig.png");

The function I wrote... I'm not sure about the getElements line...: 我写的函数...我不确定getElements行...:

var doubles = document.getElementsByTagName("img");

      doublesWidth = doubles.width;
      doublesHeight = doubles.height;

    doubles.onmouseover = function() {

       doubles.width = 2 * doublesWidth;
       doubles.height = 2 * doublesHeight;

    }

    doubles.onmouseout = function() {

       doubles.width = doublesWidth;
       doubles.height = doublesHeight;

    }

And then in the body I call the images with a height, width and src. 然后在体内,我用高度,宽度和src调用图像。 For example: 例如:

<img id="pig"  name="img2" src="pig.png" border="0" height="200" width="350">

Thanks!!!!! 谢谢!!!!!

I created a fiddle that here should help you. 我创建了一个小提琴那这里应该帮助你。 In the example, it loops over all images and applies event listeners to mouseover and mouseout , handling the image size accordingly. 在示例中,它循环遍历所有图像并将事件侦听器应用于mouseovermouseout ,从而相应地处理图像大小。

var images = document.getElementsByTagName('img');

for (var i = 0; i < images.length; i++) {
    images[i].addEventListener("mouseover", function(e) {
        e.target.width = e.target.width * 2;
    });
    images[i].addEventListener("mouseout", function(e) {
        e.target.width = e.target.width / 2;
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM