2016-01-23 136 views
2

在我的第一個項目曾經,我試圖.hover結合了.addClass()突出鼠標指針下的股利。的.addClass()似乎並沒有工作

它應該是相當簡單的,但我不能得到它的工作,這是我寫了這麼遠:

的jQuery:

$(document).ready(function() { 
    $('#NewItem').hover(function() {   
     $('#NewItem').addClass('active'); 
    }); 
}); 

CSS

div { 
    border-radius: 5px; 
    transition: background-color 0.5s ease; 
} 

#NewItem { 
    border: 1px solid #000000; 
    background-color: #F0F8FF; 
    Width: 100px; 
    height: 50px; 
    margin-left: auto; 
    margin-right: auto; 
    margin-top: 100px; 
    z-index: 5; 
    text-align: center; 
} 

.active { 
    background-color:#556677; 
} 

html

<body> 
    <div id="background"> 
     <div id="NewItem">    
      <p> Add item </p> 
     </div> 
    </div> 
</body> 

試圖找出我得到了什麼錯誤,我用「.hide()」切換了「.addclass('active')」,它確實使div消失。

回答

1

它在懸停上添加類。問題是選擇器#NewItem比選擇器.active更具體,這意味着添加了.active選擇器的背景色被覆蓋。

of #NewItem is 0,1,0,0;而.active的特異性是0,0,1,0

增加.active選擇器的specificity,並閱讀有關specificity here

Example Here

#NewItem.active { 
    background-color: #556677; 
} 

作爲一個側面說明,如果你打算來打開的mouseenter和鼠標移開類,使用可能要使用.toggleClass()方法代替:

Updated Example

$('#NewItem').hover(function() { 
    $(this).toggleClass('active'); 
}); 

或者完全避免jQuery並使用:hover僞類(如果你的情況適用):

Updated Example

#NewItem:hover { 
    background-color: #556677; 
} 
1

即使class添加,你不會得到想要的結果。原因是CSS特異性。所以改變這樣說:

#NewItem.active { 
    background-color: #556677; 
} 

#id需要更多的優先級高於.class選擇。所以兩者都可以工作。

more information,以此作爲參考:

-1

您的newitem ID的背景色覆蓋,因爲CSS具體的類活躍的背景色。請參閱下面的新工作示例。

$(document).ready(function(){ 
 

 
    $(".newItem").hover(function(){ 
 
     $(".newItem").toggleClass("active"); 
 
    }); 
 

 
});
div { 
 
    border-radius: 5px; 
 
    transition: background-color 0.5s ease; 
 
} 
 

 
.newItem { 
 
    border: 1px solid #000000; 
 
    background-color: #F0F8FF; 
 
    Width: 100px; 
 
    height: 50px; 
 
    margin-left: auto; 
 
    margin-right: auto; 
 
    margin-top: 100px; 
 
    z-index: 5; 
 
    text-align: center; 
 
} 
 

 
.active { 
 
    background-color:#556677; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<body> 
 

 
     <div id="background"> 
 
      <div class="newItem">    
 
       <p> Add item </p> 
 
      </div> 
 
     </div> 
 
</body>