前言
最近因為工作需要讓我一個效果實現在頁面某一部分內滑塊隨著滾動條上下滑動,說明一下我們項目使用技術angularJs.大家都知道,使用jquery很好實現。
那么angular如何實現呢,我用的是自定義指令(directive)。
方法如下
1.下面是我html部分代碼,detail-scroll是我自定義的標簽
...............<div id="time" style="position: relative;"> <div ng-style="maskStyle" detail-scroll style="transition: all linear 0.5s;-moz-transition:all linear 0.5s;-webkit-transition: all linear 0.5s;-o-transition: all linear 0.5s;"> <div ng-click="maskTimeDetail()"> <i class="zmdi zmdi-zoom-in" style="font-size: 22px;color: #fff;padding: 5px;"></i> </div> </div> <div class="tl-item alt" ng-repeat="time in timeList"> //..................... </div> </div>
2.開始寫js代碼
這里假設我們在某一個module下,控制器叫做AppCtrl
angular.module('xxxx',[ ]).controller('AppCtrl', ['$scope',AppCtrl]).directive('detailScroll',function(){// 返回一個函數 return{ link : function($scope,element,attr){ var container = angular.element(window); var timeH = $('#time').offset().top;//獲取該部分距離頁面頂部距離 container.on('scroll', function() { if(container.scrollTop()>timeH){ $scope.maskStyle.top = container.scrollTop()-timeH+$('#time .alt').eq(0).height()/2+'px'; } }); }, restrict:'A', //ECMA E元素 C類名 M注釋 A屬性 };});function AppCtrl($scope) { //這是我給這個滑塊定義的樣式,一定要記住你要相對應你的父級元素相對定位, //因為我們要改變是它的top值 $scope.maskStyle={ width: '30px',height: '30px', 'background-color': '#ea1c0d', 'z-index': 999, position: 'absolute', top:0,left:0, opacity:'0.8', 'text-align':'center' };}detailScroll是 angular命名規范,駝峰式,一定要這樣寫,angular只有用自定義指令,才可以用jquery的一些方法。。
以上只是個簡單的例子來演示一下,如果滑塊移動的top值不準確,可以自行計算。
這只是簡單的自定義指令寫法,還有一個是可以引入模板
angular.module('app', []) .directive('myDirective', function() { function appCtrl($scope){ //處理邏輯 } return { restrict: 'EA', replace: true, scope:{ //想要從父級controller傳到這里的函數,對象,變量,分別用(&,=,@),具體怎么用大家可以參考angular官網詳解 } templateUrl:'路徑或是html拼接的字符串', controller: function($scope, $element, $attrs, $transclude) { // 控制器邏輯 } //controller這樣寫也可以,還有一種直接寫controller名,通過注入的方法,比如 controller:['$scope',appCtrl] } })
新聞熱點
疑難解答
圖片精選