将鼠标悬停在标记类上更改img在不同元素

时间:2015-09-28 21:28:03

标签: javascript jquery html

说我有这样的事情:

<div class="right">
<article class="left_image">
<img src="images/coolestimageontheplanet.jpg" class="image_left">
</article>

然后我有一个UL列表:

    <ul class="LISTS">
      <li><a href="#link" target="_blank" class="hov5">Link 1</a></li>
       <!-- etc -->
    </ul>

我会以直接上面的标记方式获得大约10个列表项。基于悬停类,我想换掉与class="image_left"相关联的图像源,如上所示。因此,将鼠标悬停在class="hov5"上即可获得 hov5图片

2 个答案:

答案 0 :(得分:2)

您可以为mouseover&amp;添加事件监听器。 mouseleave然后相应地更改image.src,就像这样

window.addEventListener('load', function() {
  function initImageHover(selector, displaySelector) {
    var imageContainer = document.querySelectorAll(displaySelector)[0],
      elements = document.querySelectorAll(selector);

    for (var i = 0, len = elements.length; i < len; i++) {
      createHover(elements[i], imageContainer, imageContainer.src);
    };
  }

  function createHover(that, targetElement, originalImage) {

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

  initImageHover('li > a', '.image_left');
});
<div class="right">
  <article class="left_image">
    <img src="images/coolestimageontheplanet.jpg" class="image_left">
  </article>

  <ul class="LISTS">
    <li><a href="#link" target="_blank" class="hov1">Link 1</a>
    </li>
    <li><a href="#link" target="_blank" class="hov2">Link 2</a>
    </li>
    <li><a href="#link" target="_blank" class="hov3">Link 3</a>
    </li>
    <li><a href="#link" target="_blank" class="hov4">Link 4</a>
    </li>
    <li><a href="#link" target="_blank" class="hov5">Link 5</a>
    </li>
    <li><a href="#link" target="_blank" class="hov6">Link 6</a>
    </li>
    <li><a href="#link" target="_blank" data-src="http://cdn.sstatic.net/stackoverflow/img/sprites.svg?v=a7723f5f7e59" class="hov7">Link 7</a>
    </li>
  </ul>

答案 1 :(得分:1)

添加如下数据标记:

<ul class="LISTS">
      <li><a href="#link" target="_blank" class="hov5" data-img="images/newimg.jpg">Link 1</a></li>
       <!-- etc -->

然后使用这样的代码:

$("ul.LISTS>li").hover(function(){
     var imgurl = $(this).data("img");
     $(".image_left").attr("src",imgurl);
},
function(){ 
     $(".image_left").attr("src","images/coolestimageontheplanet.jpg");
});