嵌套事件侦听器未按预期更改HTML

时间:2018-12-17 16:25:04

标签: javascript addeventlistener

我已经尽力尝试了所有可行的方法,所以我一定会缺少一些东西。基本上,我正在尝试创建图像库。将鼠标悬停在每张图像上时,您可以看到作者,并且在单击图像(缩略图)时会弹出一个灯箱,其中包含更多信息。我有一个对象Hyperwall,其中包含缩略图,作者和灯箱。

我遇到麻烦的部分是关闭灯箱。 closeBtn似乎被调用,更改属性(一条打印语句显示了style.display语句得到执行),但是html却保持不变。我试过将事件侦听器从对象外部移至for循环,但这也不起作用。任何帮助表示赞赏。谢谢。

function Hyperwall(element, thumbnail, author, lightbox) {
  this.element = element;
  this.thumbnail = thumbnail;
  this.author = author;
  this.lightbox = lightbox;

  this.displayInfo = function() {
    this.element.addEventListener("mouseover", function() {
        author.style.display = "inline";
    });

    this.element.addEventListener("mouseout", function() {
        author.style.display = "none";
    });
  }

  this.displayModal = function() {
    this.element.addEventListener("click", function() {
        lightbox.style.display = "block";

        var closeBtn = lightbox.querySelector(".closeBtn");

        closeBtn.addEventListener("click", function() {
            lightbox.style.display = "none";
        });
    });
  }
}

var hyperwalls = document.getElementsByClassName("hyperwall");

for (var i = 0; i < hyperwalls.length; i++) {
  var thumbnail = hyperwalls.item(i).querySelector(".thumbnail");
  var author = hyperwalls.item(i).querySelector(".author");
  var lightbox = hyperwalls.item(i).querySelector(".lightbox");
  var current = new Hyperwall(hyperwalls.item(i), thumbnail, author, lightbox);

  current.displayInfo();
  current.displayModal();
}

0 个答案:

没有答案