为什么只有第一个鼠标悬停和鼠标停止工作?

时间:2016-09-15 22:22:23

标签: javascript html css z-index

我已加载了一组图片,并在其上应用了.mouseout().mouseover()。问题是,在第一个.mouseover()事件后,图像变大,在.mouseout()被触发后,图像将返回到之前的大小。第一次之后,Firefox中没有.mouseover()事件被触发,但在Chrome中它可以运行。问题是,Chrome z-index属性未将mouseover图像置于其他图像之上。这些问题的原因是什么?如何解决?



var images = ['http://www.rd.com/wp-content/uploads/sites/2/2016/04/01-cat-wants-to-tell-you-laptop.jpg', 'http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg', 'http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg', 'http://pershanpet.ir/wp-content/uploads/2016/05/144-jpravafcbn.jpg', 'http://www.animal-whisper.com/images/pic28.jpg'];

function loadImage(url) {
  var promise = new Promise((resolve, reject) => {
    var image = new Image();
    image.onload = function() {
      resolve(image);
    };
    image.onerror = function() {
      var msg = "could not load image at url " + url;
      reject(new Error(msg));
    };
    image.src = url;
    image.style.width = '200px';
    image.style.height = '200px';

  });
  return promise;
}

Promise.all(
  images.map(function(elem) {
    return loadImage(elem);
  })
).then((img) => {
  img.forEach(each => {

    each.addEventListener('mouseover', function(event) {

      this.style.zIndex = '2000';
      this.style.transform = 'scale(1.5,1.5)';

    });
    each.addEventListener('mouseout', function(event) {

      this.style.transform = 'scale(1,1)';
      this.style.zIndex = '-1';
    });
    addImg(each);
  });
});

function addImg(img) {
  document.body.appendChild(img);
}




2 个答案:

答案 0 :(得分:1)

也许您的图片会被z-index大于-1的其他元素所包含。在mouseout尝试this.style.zIndex = '0'

答案 1 :(得分:0)

您似乎正在将图片z-index设置为-1。有什么理由吗?

尝试在mouseout上设置this.style.zIndex = '1';