开发者

jQuery mouseover function does not work

I have a problem with jQuery. I am trying to make an image appear(or fade in) upon onmouseover event and disappear(or fade out) upon onmouseout event. The HTML that I have is:

<div class="wrapper">
<img id="mainImg" src="..." />
</div>

The CSS:

#mainImg
{
visibility:hidden;
}

And the JavaScript is as follows:

$("#mainImg").mouseover(function () {
    $(this).attr("visibility", "visible");
  }).mouseout( function () {
    $(this).attr("visibility", "hidden");
  });

But this code does not work. I am struggling to understand what is wrong but I cannot sort it out. I tested the code also in JsFiddle with no result. I also tried with the hover() function without success.

May you please tell me what I am doing wrong and propose a 开发者_JAVA百科solution? Thanks

Francesco


Visibility is not an HTML attribute; it's a CSS feature. Try using css() instead of attr().


Find working sample here: http://jsfiddle.net/ezmilhouse/MegL9/1/

you will run into problems if triggering events on invisible elements, better attach event to .wrapper:

your js:

$(".wrapper").mouseover(function () {
    $('img', this).css("visibility", "visible");
});

$(".wrapper").mouseout(function () {
    $('img', this).css("visibility", "hidden");
});

your html:

<div class="wrapper">
    <img id="mainImg" src="http://www.google.com/images/logos/ps_logo2.png" />
</div>


Actually the correct way to do that is using .toggle() function. Something like this:

$("#mainImg").mouseover(function () {
    $(this).toggle();
  }).mouseout( function () {
    $(this).toggle();
  });

Or using .hide() / .show(), like this:

$("#mainImg").mouseover(function () {
    $(this).hide();
  }).mouseout( function () {
    $(this).show();
  });

The cool thing about doing it this way is that you can specify animations for the visible / invisible transitions.

Cheers!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜