您的位置:首页 > Web前端 > AngularJS

angular实现的文字上下无缝滚动

2016-09-04 15:00 706 查看
最近在学习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中定义了需要显示的文字,接下来我们就可以开始定义指令部分。

运行效果图:



文字上下会无缝滚动,当鼠标移入是,会清除定时器,停止滚动。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: