我想在单击按钮时执行显示和隐藏。我有以下代码。我想在单击按钮“Click
”时在我的“maindiv
”内容上显示或应用我的 css 样式(color:red
)。
同样,如果我单击那个 Click
按钮,那么它应该像之前那样隐藏或显示它的正常内容(即没有任何红色的 css 样式),就像这样它应该出现。
Getting error: TypeError: Cannot read property 'classList' of null
Fiddle .
html:
<div ng-app="app">
<div ng-controller="MainController">
<div id="maindiv">
<p>Test Content</p>
</div>
<div id="mainContainer">
<div id="testId">
<button type="button" ng-click="testExpand()">Click</button>
</div>
</div>
</div>
</div>
js:
angular.module('app', []).
controller('MainController', ['$scope', function ($scope) {
$scope.testExpand = function(){
alert("testExpand is called to show");
document.querySelector("maindiv").classList.add("maindivColor");
}
}]);
最佳答案
试试angularjs的方式。
angular.module('app', []).
controller('MainController', ['$scope', function ($scope) {
$scope.testExpand = function(){
//alert("testExpand is called to show");
$scope.applyCss = !$scope.applyCss;
}
}]);
.maindivColor {
color:red;
}
.mainContainer {
border-right: 1px solid #333;
}
#testId {
// background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainController">
<div ng-class="{'maindivColor':applyCss}"><p>Normal Content</p></div>
<div ng-show="applyCss" ng-class="{'maindivColor':applyCss}">
<p>
Test Content
</p>
</div>
<div>
<button type="button" ng-click="testExpand()">Click</button>
</div>
</div>
</div>
关于html - 如何在单击按钮时应用显示和隐藏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44132834/