為什么要自定義控件?html的select 不是可以用么?以前我就是這么想的,當我接到特殊需求時,需要我自己寫一個下拉控件。
這個需求就是將圖表橫向放大,由於H5不能控制設備轉向,所以我將圖表通過css控制順時針旋轉90度。這時設備還是豎屏的,所以即使你將select空間旋轉90度,當你點擊下拉選項時,會發現選項是豎屏展示的。(不管是Android還是ios 均對h5的select 進行優化,即不在是網頁那種顯示方式,而是下方出現選項的彈框)這樣就不合適了。需要你去寫個select 組件了。
由於我使用的是Angularjs ,所以組件需要使用指定(directive) 來完成,
1 angular.module('app') 2 .directive('dropDown', [function () { 3 return { 4 restrict : 'EA', 5 replace : true, 6 transclude : true, 7 scope : { 8 selecttitle : '=', //// 默認選中值 9 lidata:'=lidata', //// 數據集如['張三','李四','王五'] 10 clickChange:'&', //// 選項變化時事件 11 disabled:'@' //// 是否顯示,支持表達式 12 }, 13 template:'<div class="ddl" ng-show="disabled">' 14 +'<div class="ddlTitle" ng-click="toggle()"><span ng-bind="selecttitle"></span><i class="fa fa-angle-down ddli"></i></div>' 15 +'<ul ng-show="showMe">' 16 +' <li ng-repeat="data in lidata" ng-click="clickLi(\'{{data}}\')">{{data}}</li>' 17 +'</ul>' 18 +'</div>', 19 link: function ($scope, $element, $attrs) { 20 21 $scope.showMe = false; 22 $scope.disabled = true; 23 24 $scope.toggle = function toggle() { 25 $scope.showMe = !$scope.showMe; 26 }; 27 28 $scope.clickLi=function clickLi(data_){ 29 $scope.selecttitle=data_; 30 $scope.showMe = !$scope.showMe; 31 }; 32 33 $scope.$watch('selecttitle', function(value) { 34 $scope.clickChange(); 35 }); 36 37 /*$scope.$watch( function() { 38 return $scope.$eval($attrs.setNgAnimate, $scope); 39 }, function(valnew, valold){ 40 $animate.enabled(!!valnew, $element); 41 });*/ 42 } 43 }; 44 }]);
Angularjs 控制器代碼
1 app.controller('***Ctl',[function(){ 2 3 $scope.currentEnttiy={}; 4 $scope.currentMetric=""; 5 6 7 $scope.initPage = function() { 8 ...... 9 $scope.changeSelect(); 10 } 11 12 13 //// 下拉選項變化時觸發 14 $scope.changeSelect=function(){ 15 ...... 16 } 17 18 $scope.initPage(); 19 20 }];
Html代碼
1 <html> 2 <head> 3 <title>hello jackical</title> 4 </head> 5 <body> 6 7 <drop-down selecttitle="currentMetric" lidata="currentEnttiy.metricNameList" click-Change="changeSelect()"></drop-down> 8 9 </body> 10 </html>
css 樣式
1 .ddl{ 2 position: relative; 3 padding:2px; 4 cursor: pointer; 5 background-color: #FAFAFA; 6 width:254px; 7 float: left; 8 } 9 .ddlTitle{ 10 height: 40px; 11 line-height: 35px; 12 padding: 2px; 13 padding-left: 5px; 14 padding-right: 5px; 15 border: solid #cccccc 1px; 16 font-size: 13px; 17 } 18 .ddlTitle span{ 19 margin-right: 10px; 20 color: #58D0E1; 21 padding-left: 5px; 22 } 23 .ddl ul li{ 24 list-style:none; 25 border-top: dotted #cccccc 1px; 26 line-height: 40px; 27 padding-left: 5px; 28 } 29 .ddl ul{ 30 position:absolute; 31 top:40px; 32 width:250px; 33 left:2px; 34 border: solid #cccccc 1px; 35 z-index: 3; 36 background-color: white; 37 padding:2px; 38 } 39 .ddli{ 40 font-size: 20px; 41 float: right; 42 margin-top: 5px; 43 }
以上為實現代碼片段。
附效果圖:
轉載請注明出處:http://www.cnblogs.com/jackicalSong/
OK ,代碼己貼完。