How to change the class on one div while hovering over another div with AngularJS?

£可爱£侵袭症+ 提交于 2020-01-12 18:35:50

问题


I want to change the class of one div while hovering over another div using AngularJS directives. Here is what I have so far 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){
}

Any ideas?


回答1:


Change my-class to myclass (i.e. the dash causes problem).

<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>

Updated: the reason my-class isn't allowed in the expression is because AngularJS treats the dash as minus symbol and tries to parse it that way. Apparently, it can't parse the statement my - class = 'highlight'. Unfortunately, after reading AngularJS parser code, I can't find a way to "help" it distinguish between dash and minus.




回答2:


You need to remove the hyphen from my-class so it will work properly in your Controller. Other than that it looks like you have it mostly done. Here's a little snippet - I also added it as text in the div so you can see it change

Your HTML File:

<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>

Controller

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


来源:https://stackoverflow.com/questions/18390473/how-to-change-the-class-on-one-div-while-hovering-over-another-div-with-angularj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!