切換狀態(tài)在前端開發(fā)中很常見,現(xiàn)在流行的網(wǎng)站中好多都用到了toggle。大多數(shù)的時(shí)候,我們需要實(shí)現(xiàn)點(diǎn)擊一個(gè)元素(一個(gè)按鈕),使得另一個(gè)DOM元素顯示和隱藏。根據(jù)這種業(yè)務(wù)需求,我相信有很多種方法來實(shí)現(xiàn)。在這篇文章中,我將分享幾個(gè)用JQuery和AngularJs實(shí)現(xiàn)它的技巧。
一、用JQuey實(shí)現(xiàn)
HTML:
<body>
<button>Custom</button>
<span>From:
<input type="text" id="from" />
</span>
<span>To:
<input type="text" id="to" />
</span>
</body>
CSS:
span {
display: none;
}
.show {
display: inline-block;
}
JS:
$("button").on("click", function () {
var state = $(this).data('state');
state = !state;
if (state) {
$("span").addClass("show");
} else {
$("span").removeClass("show");
}
$(this).data('state', state);
});
當(dāng)我們來到AngularJs的世界,我們會(huì)發(fā)現(xiàn)它與JQuery實(shí)現(xiàn)非常不同而且有趣。當(dāng)然,有很多種不同的方法實(shí)現(xiàn)它。下面是我用AngularJs實(shí)現(xiàn)ng-toggle的小技巧。
二、用AngularJs實(shí)現(xiàn)
HTML:
<body ng-app="ngToggle">
<div ng-controller="AppCtrl">
<button ng-click="toggleCustom()">Custom</button>
<span ng-hide="custom">From:
<input type="text" id="from" />
</span>
<span ng-hide="custom">To:
<input type="text" id="to" />
</span>
<span ng-show="custom"></span>
</div>
</body>
JS:
angular.module('ngToggle', [])
.controller('AppCtrl',['$scope', function($scope){
$scope.custom = true;
$scope.toggleCustom = function() {
$scope.custom = $scope.custom === false ? true: false;
};
}]);