Swap DIV class on hover with jQuery

2019-06-01 03:18发布

This is what I'm trying to achieve :

2 DIV's, on page load the first DIV is visible, on hover it switches to the second DIV (which is initially hidden).

Both DIV's are the same height and width and are positioned absolutely within the wrapper.

This is what i've got so far, but it's not working properly -

JS :

 (function($) { 
 $(".wrap").hover(function() {
 $(".first,.second", this).toggle();
 })
 })( jQuery );

CSS :

 .wrap {position:relative;}

 .first {
 position:absolute;
 top:0;
 padding:20px;
 width:80px;
 height:80px;
 background:green;
 color:white;
 display:block;
 }

 .second {
 position:absolute;
 top:0;
 padding:20px;
 width:80px;
 height:80px; 
 background:yellow;
 color:blue;
 display:block;
 visibility:hidden;
 }

HTML :

<div class="wrap">
<div class="first">FIRST DIV</div>
<div class="second">SECOND DIV</div>
</div>

Here is a working FIDDLE so you can see what's happening.

Any suggestions?

1条回答
\"骚年 ilove
2楼-- · 2019-06-01 04:01

Dont Use visibility:hidden, instead use display:none

.second {
      position:absolute;
      top:0;
      padding:20px;
      width:80px;
      height:80px; 
      background:yellow;
      color:blue;
      display:none;
}

Working Demo

查看更多
登录 后发表回答