前言
最近因?yàn)楣ぷ餍枰屛乙粋€(gè)效果實(shí)現(xiàn)在頁面某一部分內(nèi)滑塊隨著滾動(dòng)條上下滑動(dòng),說明一下我們項(xiàng)目使用技術(shù)angularJs.大家都知道,使用jquery很好實(shí)現(xiàn)。
那么angular如何實(shí)現(xiàn)呢,我用的是自定義指令(directive)。
方法如下
1.下面是我html部分代碼,detail-scroll是我自定義的標(biāo)簽
............... <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代碼
這里假設(shè)我們?cè)谀骋粋€(gè)module下,控制器叫做AppCtrl
angular.module('xxxx',[ ]) .controller('AppCtrl', ['$scope',AppCtrl]) .directive('detailScroll',function(){ // 返回一個(gè)函數(shù) 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) { //這是我給這個(gè)滑塊定義的樣式,一定要記住你要相對(duì)應(yīng)你的父級(jí)元素相對(duì)定位, //因?yàn)槲覀円淖兪撬膖op值 $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命名規(guī)范,駝峰式,一定要這樣寫,angular只有用自定義指令,才可以用jquery的一些方法。
以上只是個(gè)簡(jiǎn)單的例子來演示一下,如果滑塊移動(dòng)的top值不準(zhǔn)確,可以自行計(jì)算。
這只是簡(jiǎn)單的自定義指令寫法,還有一個(gè)是可以引入模板
angular.module('app', []) .directive('myDirective', function() { function appCtrl($scope){ //處理邏輯 } return { restrict: 'EA', replace: true, scope:{ //想要從父級(jí)controller傳到這里的函數(shù),對(duì)象,變量,分別用(&,=,@),具體怎么用大家可以參考angular官網(wǎng)詳解 } templateUrl:'路徑或是html拼接的字符串', controller: function($scope, $element, $attrs, $transclude) { // 控制器邏輯 } //controller這樣寫也可以,還有一種直接寫controller名,通過注入的方法,比如 controller:['$scope',appCtrl] } })
可以參考這個(gè)//www.gxlcms.com/article/107045.htm,很詳細(xì)~~~
總結(jié)
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com