具有悬停角度的ngClass

时间:2014-12-21 20:03:16

标签: html css angularjs

让我说我有这个:

 <div 
     class="italic" 
     ng-class="{red: hover}" 
     ng-mouseenter="hover = true"
     ng-mouseleave="hover = false">
         Test 1 2 3.
    </div>
     <div 
     class="italic" 
     ng-class="{red: hover}" 
     ng-mouseenter="hover = true"
     ng-mouseleave="hover = false">
         Test 1 2 3.
    </div>  

当用户悬停div时,我想用红色类改变颜色。但现在当盘旋两个div变红时 使用代码

[Fiddle] 1

3 个答案:

答案 0 :(得分:1)

您需要使用指令

.directive('hoverClass', function () {
    return {
        restrict: 'A',
        scope: {
            hoverClass: '@'
        },
        link: function (scope, element) {
            element.on('mouseenter', function() {
                element.addClass(scope.hoverClass);
            });
            element.on('mouseleave', function() {
                element.removeClass(scope.hoverClass);
            });
        }
    };
});

并添加此html

<div class="italic" hover-class="red" >
     Test 1 2 3.
</div>  

试试这个http://jsfiddle.net/pthfV/238/

答案 1 :(得分:0)

<div class="italic" ng-repeat="item in items" ng-mouseover="hoverSelect($index)" 
ng-mouseleave="hoverDeselect($index)" ng-class="{red: $index == {{active}}}">


Controller:
$scope.hoverSelect = function(index) {
     $scope.active = index;
     }

$scope.hoverDeselect = function(index) {
     $scope.active = '';
     }

答案 2 :(得分:0)

您不需要指令或功能。你只需要为每个div提供一个单独的变量。这可能是hover1 vs hover2hovers.div1 vs hovers.div2,甚至hover[0] vs hover[1]。如果两个div都基于相同的变量,则两个div都将始终执行操作。

http://jsfiddle.net/pthfV/841/