>本教程演示了使用Angularjs構建幻燈片插件,從而避免使用更清潔,更簡潔的代碼庫。 我們利用角指令和動畫來實現這一目標。 假定對AngularJS指令的熟悉。
鍵優點:
>
我們首先創建一個孤立的angularjs指令:
slider
是隔離的,以防止與父範圍的衝突。
<code class="language-javascript">var sliderApp = angular.module('sliderApp', ['ngAnimate']); // Note: ngAnimate included sliderApp.directive('slider', function($timeout) { return { restrict: 'AE', replace: true, scope: { images: '=' }, link: function(scope, elem, attrs) { scope.currentIndex = 0; scope.next = function() { scope.currentIndex = (scope.currentIndex + 1) % scope.images.length; }; scope.prev = function() { scope.currentIndex = (scope.currentIndex - 1 + scope.images.length) % scope.images.length; }; scope.$watch('currentIndex', function() { scope.images.forEach(function(image) { image.visible = false; }); scope.images[scope.currentIndex].visible = true; }); var timer; var sliderFunc = function() { timer = $timeout(function() { scope.next(); timer = $timeout(sliderFunc, 5000); // Adjust interval as needed }, 5000); }; sliderFunc(); scope.$on('$destroy', function() { $timeout.cancel(timer); }); }, templateUrl: 'templates/templateurl.html' }; });</code>包括用於動畫支持。
scope
>images
>步驟2:圖像數據控制器ngAnimate
一個控制器提供圖像數據:
)
<code class="language-javascript">sliderApp.controller('SliderController', function($scope) { $scope.images = [ { src: 'img1.png', title: 'Pic 1' }, { src: 'img2.jpg', title: 'Pic 2' }, { src: 'img3.jpg', title: 'Pic 3' }, { src: 'img4.png', title: 'Pic 4' }, { src: 'img5.png', title: 'Pic 5' } ]; });</code>>
指令的html模板使用顯示圖像:templates/templateurl.html
ng-repeat
<code class="language-html"><div class="slider"> <div class="slide" ng-repeat="image in images" ng-show="image.visible"> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Creating a Slide Show Plugin With AngularJS - SitePoint"> <p>{{image.title}}</p> </div> <div class="arrows"> <a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b" ng-click="prev()"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174018895287877.png" class="lazy" alt="Creating a Slide Show Plugin With AngularJS - SitePoint"></a> <a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b" ng-click="next()"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174018895383537.png" class="lazy" alt="Creating a Slide Show Plugin With AngularJS - SitePoint"></a> </div> </div></code>
步驟5:使用指令
> 在您的主HTML中,包括指令和控制器:記住要包含用於設計滑塊的必要CSS。 此增強示例包括自動幻燈片功能和改進的錯誤處理。 切記用實際的圖像URL替換佔位符圖像路徑。 添加了
<code class="language-css">.slide.ng-hide-add, .slide.ng-hide-remove { transition: opacity 0.5s linear; } .slide.ng-hide-add.ng-hide-add-active, .slide.ng-hide-remove { opacity: 0; } .slide.ng-hide-add, .slide.ng-hide-remove.ng-hide-remove-active { opacity: 1; }</code>屬性以供可訪問性。
以上是使用AngularJS創建幻燈片顯示插件-SitePoint的詳細內容。更多資訊請關注PHP中文網其他相關文章!