繁体   English   中英

javascript 图片放大缩小

[英]javascript picture zoom in and zoom out

我尝试创建一个 javascript class 来放大和缩小一些图片。 但是页面的所有图片都会放大和缩小。 我认为这是 javascript 循环的问题,但我做不到。 这是我的 Class,有人看到问题了吗?

class 图像 {

constructor() {
    this.ip = document.getElementsByClassName("image_petite");
    this.images = [];
}

agrandir() {
   
    for (let i=0; i < this.ip.length; i++) {
        this.images.push(this.ip[i]);
        };

    console.log(this.images);

for (let j=0; j < this.images.length; j++) {
    if (this.images[j].classList == "image_petite") { 
    
        this.images[j].classList.remove('image_petite');
        this.images[j].classList.add('image_grande');
        
        
        } else if (this.images[j].classList == "image_grande") {
        this.images[j].classList.remove('image_grande');
        this.images[j].classList.add('image_petite');
        }
        }            
}

}

let image = new Image();

this.images[j].classList == "image_petite"不是您检查元素是否具有 class 的方式。 相反,您使用contains

if (this.images[j].classList.contains("image_petite")) {
    // ...
}

但是,另外,您使用了一个循环,它有意处理this.images数组中的所有内容。 如果不知道 DOM 结构(大致是 HTML)是什么样子,很难说应该做什么,但是如果您尝试调整一张图像的大小,则需要确定要调整大小的图像,即该代码中没有任何内容。

这是一个使用click处理程序的简单示例:

 // This example uses event delegation document.body.addEventListener("click", event => { const image = event.target.closest("img"); if (image && event.currentTarget.contains(image)) { // This is the image to enlarge or toggle if (image.classList.contains("image_grand")) { // Toggling it from big back to small image.classList.remove("image_grand"); image.classList.add("image_petite"); } else { // Making this the one big one const big = document.querySelector(".image_grand"); if (big) { // Make the current big one small again big.classList.remove("image_grand"); big.classList.add("image_petite"); } // Make this one big image.classList.add("image_grand"); image.classList.remove("image_petite"); } } });
 .image_petite { width: 75px; height: 75px; }.image_grand { width: 150px; height: 150px; }
 <div> <img class="image_petite" src="https://via.placeholder.com/150/0000FF/808080?text=1"> </div> <div> <img class="image_petite" src="https://via.placeholder.com/150/0000FF/808080?text=2"> </div> <div> <img class="image_petite" src="https://via.placeholder.com/150/0000FF/808080?text=3"> </div>

也就是说,我想我只使用一个 class 并添加/删除 class,而不是两个类。

1000 谢谢你,你的代码完美运行!

暂无
暂无

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

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