How can I display an image in a div if <a> is hovered over?

拜拜、爱过 提交于 2019-12-24 00:59:58

问题


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?


回答1:


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.




回答2:


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

FIDDLE




回答3:


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


来源:https://stackoverflow.com/questions/12254383/how-can-i-display-an-image-in-a-div-if-a-is-hovered-over

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!