鼠标输出返回原始图像源

时间:2015-09-28 22:58:05

标签: javascript

我正在使用下面的代码操作图像源,效果很好,但是我没有添加鼠标输出功能(所以当没有悬停在指定的<li>之一上时)的图像源是在下面的代码中更改,返回到任何悬停发生之前的状态,是否有任何想法?

window.addEventListener('load', function() {
  var imageContainer = document.querySelectorAll('.image_left')[0];

  function initImageHover(selector) {
    var elements = document.querySelectorAll(selector);
    console.log(elements);
    for (var i = 0, len = elements.length; i < len; i++) {
      createHover(elements[i]);
    };
  }

  function createHover(that) {
    that.addEventListener('mouseover', function() {
      var src = that.getAttribute('data-src');
      if (src) {
        imageContainer.src = src;
      }
    });
    that.addEventListener('mouseleave', function() {
      imageContainer.src = '';
    });
  }

  initImageHover('li.one > a');
});

window.addEventListener('load', function() {
  var imageContainer = document.querySelectorAll('.image_left2')[0];

  function initImageHover(selector) {
    var elements = document.querySelectorAll(selector);
    console.log(elements);
    for (var i = 0, len = elements.length; i < len; i++) {
      createHover(elements[i]);
    };
  }

  function createHover(that) {
    that.addEventListener('mouseover', function() {
      var src = that.getAttribute('data-src');
      if (src) {
        imageContainer.src = src;
      }
    });
    that.addEventListener('mouseleave', function() {
      imageContainer.src = '';
    });
  }

  initImageHover('li.two > a');
});

更新原始图片;在li元素之外,并且在下面标记。目前只是通过两次回答尝试获取图像无效/死图像。

<div class="block2wrap">
<div class="left">
<article class="left_image">
<img src="images/verycoolimage.jpg" class="image_left">
</article>

2 个答案:

答案 0 :(得分:3)

将原始图像src保存在变量中,并在鼠标离开时使用它:

function createHover (that) {

  var original = that.getAttribute('src');

  that.addEventListener('mouseover', function() {
    var src = that.getAttribute('data-src');
    if (src) {
      imageContainer.src = src;
    }
  });
  that.addEventListener('mouseleave', function() {
    imageContainer.src = original;
  });
}

这是fiddle

答案 1 :(得分:1)

将此行添加到鼠标悬停功能(在设置src之前)

var _src = that.getAttribute('src');
that.setAttribute('data-old-src', _src);

在mouseleave中更改此行

imageContainer.src = '';

到那个

imageContainer.src = that.getAttribute('data-old-src');