最近在學習angularJs,業余時間隨便寫了一個文字上下無縫滾動的例子,主要寫了一個小小的指令。
css代碼:主要控制樣式
<style type="text/css"> *{margin: 0px;padding: 0px;} .slide {width: 200px;height:200px;border:1px solid #dcdcdc;margin: 0 auto;margin-top: 50px;overflow: hidden;} .slide li {height: 49px;line-height: 49px;text-align: left;padding: 0 10px;font-size: 16px;list-style: none;border-bottom: 1px dashed #dcdcdc;cursor: pointer;} .slide li:hover{background: #ccc;} </style>
html代碼:
<body ng-app="tip"> <div ng-controller = "TipController"> <div class="slide"> <ul class="slideUl"> <!-- 指令 --> <slide-follow id="slide" dataset-data = "datasetData"></slide-follow> </ul> </div> </div> </body>
當然我們的代碼都是基於頁面中已經引入angular.js文件下來運行的
slide-follow是我們需要實現的指令 dataset-data = "datasetData" 是我們需要顯示的文字
js代碼
<script type="text/javascript"> var app =angular.module("tip",[]); app.controller("TipController",function($scope){ // 數據可以根據自己使用情況更換 $scope.datasetData = [ {option : "這個是第一條數據"}, {option : "這個是第二條數據"}, {option : "這個是第三條數據"}, {option : "這個是第四條數據"}, {option : "這個是第五條數據"}, {option : "這個是第六條數據"} ] }) .directive("slideFollow",function($timeout){ return { restrict : 'E', replace : true, scope : { id : "@", datasetData : "=" }, template : "<li ng-repeat = 'data in datasetData'>{{data.option}}</li>", link : function(scope,elem,attrs) { $timeout(function(){ var className = $("." + $(elem).parent()[0].className); var i = 0,sh; var liLength = className.children("li").length; var liHeight = className.children("li").height() + parseInt(className.children("li").css('border-bottom-width')); className.html(className.html() + className.html()); // 開啟定時器 sh = setInterval(slide,4000); function slide(){ if (parseInt(className.css("margin-top")) > (-liLength * liHeight)) { i++; className.animate({ marginTop : -liHeight * i + "px" },"slow"); } else { i = 0; className.css("margin-top","0px"); } } // 清除定時器 className.hover(function(){ clearInterval(sh); },function(){ clearInterval(sh); sh = setInterval(slide,4000); }) },0) } } }) </script>
首先我們在controller中定義了需要顯示的文字,接下來我們就可以開始定義指令部分。
運行效果圖:
文字上下會無縫滾動,當鼠標移入是,會清除定時器,停止滾動。