【问题标题】:How to change the class on one div while hovering over another div with AngularJS?如何在使用 AngularJS 将鼠标悬停在另一个 div 上时更改一个 div 上的类?
【发布时间】:2013-08-22 20:44:23
【问题描述】:

我想在使用 AngularJS 指令将鼠标悬停在另一个 div 上时更改一个 div 的类。这是我目前所拥有的http://jsfiddle.net/E8nM5/38/

HMTL

<div ng-controller="Ctrl" ng-app>
   <div ng-class="my-class">This div will change class when one hovers over bottom DIV </div>
   <br/>
   <div class="hover-div" ng-mouseenter="my-class = 'highlight'" ng-mouseleave="my-class = 'lowlight'">HOVER OVER ME TO CHANGE THE UPPER DIV's CLASS</div>    
</div>

CSS

div.highlight {
    padding: 10px;
    background: red;
    color: white;
}

div.lowlight {
    padding: 10px;
    background: blue;
    color: white;
}

div.hover-div {
    padding: 10px;
    background: green;
    color: white;
}

JS

function Ctrl($scope){
}

有什么想法吗?

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    my-class 更改为myclass(即破折号会导致问题)。

    <div ng-controller="Ctrl" ng-app>
        <div ng-class="myclass">This div will change class when one hovers over bottom DIV </div>
        <br/>
        <div class="hover-div" ng-mouseenter="myclass = 'highlight'" ng-mouseleave="myclass = 'lowlight'">HOVER OVER ME TO CHANGE THE UPPER DIV's CLASS</div>    
    </div>
    

    更新: 表达式中不允许使用my-class 的原因是因为AngularJS 将破折号视为减号并尝试以这种方式解析它。显然,它无法解析语句my - class = 'highlight'。不幸的是,在阅读了 AngularJS 解析器代码后,我找不到一种方法来“帮助”它区分破折号和减号。

    【讨论】:

    • 没有理由区分两者。 my-class 是无效的 Javascript 变量名。就是这样。应该明白myclass 是一个Javascript 变量,而不是一个CSS 类。所以如果是JS而不是CSS要遵循的命名规则。
    • @siddhant3s 可以指定$scope['my-class'] = ...,既是有效的JS,又是AngularJS。所以 OP 提出了一个完全合理的问题,如果 AngularJS 可以支持它肯定会有所帮助。
    【解决方案2】:

    您需要从 my-class 中删除连字符,这样它才能在您的 Controller 中正常工作。除此之外,看起来你已经完成了大部分工作。这是一个小 sn-p - 我还将它作为文本添加到 div 中,以便您可以看到它的变化

    您的 HTML 文件:

    <div class="{{myClass}}"> {{myClass}} </div>
        
         <div class="hover" style="height:50px; width:50px; border:1px solid black;" ng-mouseleave="myClass='test'" ng-mouseenter="myClass='hola'"> </div>
    

    控制器

    function Ctrl($scope){
        $scope.myClass="test";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-30
      • 2015-09-12
      • 1970-01-01
      相关资源
      最近更新 更多