2016-01-23 227 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>