js代碼
/** * @ngdoc directive * @name myToggle * @module index * @restrict E */(function () { 'use strict'; var jqLite = angular.element, forEach = angular.forEach; angular.module('index.directive', []) .directive('myToggle', IndexDirective); // function IndexDirective() { var obj = { restrict: 'E', replace: true, require: '?ngModel', transclude: true, template: '<div class="item item-toggle">' + '<div ng-transclude></div>' + '<label class="toggle">' + '<input type="checkbox">' + '<div class="track">' + '<div class="handle"></div>' + '</div>' + '</label>' + '</div>', compile: function (element, attr) { var input = element.find('input'); //在作用域沒綁定前,修改DOM forEach({ 'ng-model': attr.ngModel }, function (value, name) { input.attr(name, value); }); return function ($scope, $ele) { var checkbox = $ele[0].getElementsByTagName('input')[0]; //獲得多選框元素的指定控制器實(shí)例 var ngModelController = jqLite(checkbox).controller('ngModel'); //監(jiān)聽多選框的事件 jqLite(checkbox).on('change', checkbox_change); if ($scope.user.open) { checkbox.checked = true; } else { checkbox.checked = false; } function checkbox_change() { //當(dāng)觸發(fā)多選框事件時(shí),改變變量 if (ngModelController) { ngModelController.$setViewValue(checkbox.checked); $scope.$apply(); } } }; } }; return obj; }})();
css代碼
.toggle { position: relative; display: inline-block; pointer-events: auto; margin: -5px; padding: 5px; } .toggle input:checked + .track { border-color: #4cd964; background-color: #4cd964; } .toggle input { display: none; } .toggle .track { -webkit-transition-timing-function: ease-in-out; transition-timing-function: ease-in-out; -webkit-transition-duration: 0.3s; transition-duration: 0.3s; -webkit-transition-property: background-color, border; transition-property: background-color, border; display: inline-block; box-sizing: border-box; width: 51px; height: 31px; border: solid 2px #e6e6e6; border-radius: 20px; background-color: #fff; content: ' '; cursor: pointer; pointer-events: none; } .toggle .handle:before { position: absolute; top: -4px; left: -21.5px; padding: 18.5px 34px; content: " "; } .toggle input:checked + .track .handle { -webkit-transform: translate3d(20px, 0, 0); transform: translate3d(20px, 0, 0); background-color: #fff; } .item-toggle .toggle { position: absolute; top: 10px; right: 16px; z-index: 3; } .toggle input:disabled + .track { opacity: 0.6; } .toggle .handle { -webkit-transition: 0.3s cubic-bezier(0, 1.1, 1, 1.1); transition: 0.3s cubic-bezier(0, 1.1, 1, 1.1); -webkit-transition-property: background-color, transform; transition-property: background-color, transform; position: absolute; display: block; width: 27px; height: 27px; border-radius: 27px; background-color: #fff; top: 7px; left: 7px; box-shadow: 0 2px 7px rgba(0, 0, 0, 0.35), 0 1px 1px rgba(0, 0, 0, 0.15); } </style>
聯(lián)系客服