How can I display an image in a div if is hove

2019-07-16 01:38发布

I have

<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>

I want the corresponding image to appear in the div if hovered and see nothing in a div, if not hovered. How to make it using jQquery?

3条回答
看我几分像从前
2楼-- · 2019-07-16 02:05

I'd suggest:

$('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.

查看更多
欢心
3楼-- · 2019-07-16 02:11

You could add an attribute to your hrefs, like

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

And add some simple Script like

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); } }
}
查看更多
老娘就宠你
4楼-- · 2019-07-16 02:18
$('#my-ul a').on('mouseenter mouseleave', function(e) {
    $('#imgs img').eq($(this).parent('li').index()).toggle(e.type==='mouseenter');
});

FIDDLE

查看更多
登录 后发表回答