2016-03-01 46 views
0

我正在製作一組照片/文字。除了第一個在頁面加載時具有活動類的頁面以外,所有面板都將具有覆蓋顏色,除去覆蓋頁面。當您將鼠標懸停在第二/第三個面板上時,疊加活動類將從第一個面板中移除並進入懸停的面板。移除和添加懸停類

現在它只在頁面加載時有效,我似乎無法從第一個div跳到第二個div。

if ($(".overlay:first")){ 
    $(".overlay:first").addClass("active"); 
    } 

else { 
    if ($(".overlay:not(:first)").hover){ 
      $(".overlay:first").removeClass("active"); 
      } 

     }  

https://jsfiddle.net/egdkuh16/3/

回答

2

沒有必要使用JavaScript或jQuery的這一點。它最好用於CSS與:hover僞選擇器。今天也很容易。

.overlay:first-child { 
    background: white; 
} 

.overlay:first-child:hover { 
    background: gold; 
} 

如果你堅持使用jQuery,你可以試試這個

$(".overlay:first").on("mouseover", function() { 
 
    $(this).addClass("active"); 
 
}).on("mouseout", function() { 
 
    $(this).removeClass("active"); 
 
});
.active { 
 
    background: gold; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="overlay">First overlay class</div> 
 
<div class="overlay">Second overlay class</div>

這種方法是高度後,雖然

+0

是的,我在想jQuery的 –

+0

但怎麼會在頁面加載該CSS工作,不會對第一個div覆蓋,然後懸停在另一格採取過的第一個元素? – runningantelope123

0

在jQuery中,你可以做這樣皺起了眉頭這個:

$(document).ready(function() { 

    // Make the first active 
    $(".overlay:first").addClass("active"); 

    // On hover remove all active classes from .overlay 
    // and add .active only to the one that is hovered 
    $(".overlay").hover(function() { 
    $(".overlay").removeClass("active"); 
    $(this).addClass("active"); 
    }); 

}); 

但理查德漢密爾頓的答案更好,更清潔。

0

您可以使用jQuery的on。例如:

$(".overlay:first").addClass("active"); 
$(".overlay").on("hover", function(){ 
    $(this).addClass("active"); 
    $(".overlay:first").removeClass("active") 
});