如果<a> is hovered over?</a>我如何在div中显示图像

时间:2012-09-03 21:47:51

标签: jquery css html hover

我有

<script>
//some jQuery code is here to see img1.jpg if hovered on .img1; 
//img2.jpg if hovered on .img2;
//img3.jpg if hovered on .img3
</script>

    <div id="imgs">
    <img src="img1.jpg" alt="">
    <img src="img2.jpg" alt="">
    <img src="img3.jpg" alt="">
    </div>

    <ul id="my-ul">
    <li><a href="#" class="img1">hover to see image1</a></li>
    <li><a href="#" class="img2">hover to see image2</a></li>
    <li><a href="#" class="img3">hover to see image3</a></li>
    </ul>

我希望相应的图像出现在div中,如果悬停并在div中看不到任何内容,如果没有悬停。 如何使用jQquery制作它?

3 个答案:

答案 0 :(得分:3)

我建议:

$('li a').hover(
    function(){
        var i = $(this).parent('li').index();
        $('#imgs img:eq(' + i + ')').show();
    },
    function(){
        var i = $(this).parent('li').index();
        $('#imgs img:eq(' + i + ')').hide();
    });

JS Fiddle demo

答案 1 :(得分:3)

$('#my-ul a').on('mouseenter mouseleave', function(e) {
    $('#imgs img').eq($(this).parent('li').index()).toggle(e.type==='mouseenter');
});

FIDDLE

答案 2 :(得分:0)

您可以为href添加属性,例如

<a href="#" title="img1.jpg" onmouseover="void(hoverImg(this));">asdf</a>

添加一些简单的脚本,如

function hoverImg(_src)
{
   // Set this to true in order to troubleshoot the script
   var _debugThis = false;

   try
   {
      var _iSrc = _src.getAttribute('title');
      var _iTrg = document.getElementById('imgs');
      var _img=document.createElement('img');
      _img.src=_iSrc;
      // other attributes for your image
      _iTrg.innerHTML=null;
      _iTrg.appendChild(_img);
      // inject unhover trigger
      _iSrc.onmouseout=function(){void(document.getElementById('imgs').innerHTML=null);}
   }
   catch (_e) { if (_debugThis) { alert(_e); } }
}