如何让DOM操作在图片上工作?

问题描述 投票:0回答:2

我想通过DOM操作让图片在点击时调整大小。我正在尝试下面的代码,但它不工作。

var images = document.getElementsByTagName("img")

//these 12 images are stored in var 'images' but do not react when clicked.

images.addEventListener("click", function() {
    height: "500px";
    width: "500px"
});

//JS and HTML files are connected.
javascript html dom
2个回答
2
投票

你的代码有两个主要问题。

  1. 你没有给图片添加事件监听器,而是把它添加到图片集合中。这并不是将它添加到集合中的每一个单独的图像,所以你必须手动完成。

  2. 这一行 height: "500px"; 是一个变量赋值,并不能改变图像的样式。你必须直接设置样式。

为了解决这些问题。

  1. 在数组上迭代,然后给每张图片添加事件监听器
for (let image of images) {
    image.addEventListener("click", function() {
        // Code goes here
    });
}
  1. 直接改变图像的风格
image.style.height = "500px";
image.style.width = "500px";

最终的结果会是这样的。

for (let image of images) {
    image.addEventListener("click", function() {
       image.style.height = "500px";
       image.style.width = "500px";
    });
}

1
投票

你不能只通过直接将事件处理程序附加到一个集合上。javascript,在 jquery 你可以做一些类似的事情(但我很确定它只是通过封装来迭代集合)。你需要对集合进行迭代,然后将事件监听器添加到集合中的每个元素。

for(let x = 0; x < images.length; x++){
    images[x].addEventListener("click", function() {
       this.style.height = "500px";
       this.style.width = "500px";
    });
}

1
投票

我发现你的代码中有两个错误


1) 你调用了 addEventListener 的数组上。

getElementsByTagName 返回一个节点数组,你需要在每个节点上手动添加事件,像这样。

for (var i = 0; i < images.length; i++) {
    images[i].addEventListener(...);
}

2) 你在Javascript上下文中输入了CSS:)

函数的内容必须是Javascript代码而不是CSS。

这应该是可行的。

images[i].addEventListener("click", function() {
   this.style.height = "500px";
   this.style.width = "500px";
});

最终的结果会是这样的。

for (var i = 0; i < images.length; i++) {
    images[i].addEventListener("click", function() {
       this.style.height = "500px";
       this.style.width = "500px";
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.