2015-06-08 150 views
1

HTML如何在點擊某個項目時設置背景顏色?

<ul class="ul_nav"> 
    <li ng-class="class" ng-click="changeClass()">Marketing</li> 
    <li ng-class="class" ng-click="changeClass()">Sells Team Nestle</li> 
    <li ng-class="class" ng-click="changeClass()">Marketing Test</li> 
    <li ng-class="class" ng-click="changeClass()">Marketing </li>     
</ul> 

Angularjs

$scope.changeClass = function(){ 
     if ($scope.class === "nav_color") 
      $scope.class = "nav_active"; 
     else 
      $scope.class = "nav_color"; 
    }; 

CSS

.ul_nav{ 
    margin-top:15px; 
    list-style:none; 
    padding:0; 
    height:600px; 
} 
.ul_nav > li{ 
    padding: 3px 0 3px 25px; 
    cursor:pointer; 
} 

.ul_nav > li:hover{ 
    background:#ff9900; 
    color:#fff; 
} 
.nav_color{ 
    background:#fff; 
    color:#000; 
} 
.nav_active{ 
    background:#ff9900; 
    color:#fff; 
} 

在這裏,我可以改變導航的背景顏色。但是當我點擊一個項目時,它會改變所有4項目的背景顏色。如何解決這個問題。 Plunker

+0

你創建一個使用NG-重複這個'li'的..? –

回答

3

HTML:

<ul class="ul_nav"> 
    <li ng-class="{class : classVar==='Marketing" }' ng-click="changeClass('Marketing')">Marketing</li> 
    <li ng-class="{class : classVar==='Sells' }" ng-click="changeClass('Sells')">Sells Team Nestle</li> 
    <li ng-class="{class : classVar==='MarketingTest' }" ng-click="changeClass('MarketingTest')">Marketing Test</li> 
    <li ng-class="{class : classVar==='Marketing1' }" ng-click="changeClass('Marketing1')">Marketing </li>     
</ul> 

JS:

$scope.changeClass = function(value){ 
     $scope.classVar= value; 
    }; 
    $scope.myVar = false; 
    $scope.toggle = function() { 
     $scope.myVar = !$scope.myVar; 
    }; 

入住這Plunker

0

您需要在代碼更改下面。

標記

<ul class="ul_nav"> 
    <li ng-class="class1" ng-click="changeClass('class1')">Marketing</li> 
    <li ng-class="class2" ng-click="changeClass('class2')">Sells Team Nestle</li> 
    <li ng-class="class3" ng-click="changeClass('class3')">Marketing Test</li> 
    <li ng-class="class4" ng-click="changeClass('class4')">Marketing </li> 
</ul> 

代碼

$scope.changeClass = function(className) { 
    className = (className === "nav_color") ? "nav_active" : "nav_color"; 
}; 

Plunkr here