javascript - 为什么只有第一个鼠标悬停和鼠标移开有效?

标签 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);
}

最佳答案

也许您的图像在 z-index 大于 -1 的其他元素下。在 mouseout 上尝试 this.style.zIndex = '0'

关于javascript - 为什么只有第一个鼠标悬停和鼠标移开有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39521193/

相关文章:

javascript - 如何滚动到照片库中的下一个缩略图

javascript - 移动到滚动的 div 元素

javascript - 文本在侧面菜单关闭时折叠

html - 加载骨架效果作为图像的背景颜色

javascript - Fabric 3.4.0 文本格式

javascript - Chrome扩展程序突然出现错误: "cannot access before initialization"

javascript - 计算测验结果

html - 梯形截面,剪裁背景图像

javascript - 悬停文本上的 slider

html - 在 CSS/HTML 中命名和调用元素