Can't use CSS ID selector for angular animate

2019-08-09 19:30发布

问题:

My checkbox input toggles my myDiv using ng-show. I would like this to look fancy. Thus, I'm using a transition effect, using angular-animate.js.

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js"></script>
<script>
    var app=angular.module('ang_app', ['ngAnimate']);
    app.controller('ang_control01_main', function($scope) {

    });
</script>
<style>
    div {
        transition: .5s;
        height: 100px;
        background-color:lightblue;
    }
    .ng-hide { /* using .ng-show here doesn't work btw */
        height: 0;
    }
</style>
<body ng-app="ang_app" ng-controller="ang_control01_main">
    <input type="checkbox" ng-model="myCheck">
    <div id="myDiv" ng-show="myCheck"></div>
</body>

(http://jsfiddle.net/gfwrknpr/)

Works fine.

However, if I change the selector from div to #myDiv, the animation is gone. Why?

回答1:

change your css to:

#myDiv{
    transition: .5s;
    height: 100px;
    background-color:lightblue;
}
#myDiv.ng-hide { /* using .ng-show here doesn't work btw */
    height: 0;
}

and it will work