实现思路
滚动内容的left值初始化为外部box宽度(注意:css中设置相对定位);
每0.05s ,left值-2,直到left值=-滚动内容宽度,证明滚动到头了(此处可根据实际体验效果设置具体数值);
此刻,回归最右侧,left=box宽度。
html代码如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css" media="all">
.d1{
margin:10px auto;
width:100%;
background-color:#CCCCCC;
height:20px;
overflow:hidden;
white-space:nowrap;
position: relative;
}
.d2{
margin:0px auto;
background-color:#FF9933;
}
.div2{
width:auto;
height:20px;
font-size:12px;
position: absolute;
left:100%;
}
.notice-item-in{
margin-right: 150px;
}
.notice-item-in:last-child{
margin-right: 0;
}
</style>
</head>
<body ng-app="app" ng-controller="appController">
<div class="d1" id="div1">
<span class="div2" id="div2">
<span class="notice-item-in" ng-repeat="notice in noticeList">{{notice.content}}</span>
</span>
</div>
</body>
</html>
<script src="jquery-1.9.1.min.js"></script>
<script src="angular.js"></script>
<script src="scroll.js"></script>
js代码如下:
var app = angular.module('app',[]);
angular.module('app').controller( 'appController', ['$scope', '$rootScope','$timeout','$interval', function($scope,$rootScope,$timeout,$interval) {
$scope.noticeList=[{"content":"第一个"}];
$interval(function() {
$scope.noticeList=[{"content":"第一个"},{"content":"我是新建的内容我是新建的内容"},{"content":"我是新建的内容我是新建的内容"}];
}, 2000)
//设置滚动内容的left值
function offset(dom, direct, size) {
$(dom).css(direct, size);
}
function noticeScroll(){
var boxBarWidth = $(window).width()-150;
var scrollBarWidth = $('#scroll-item').width();
//var maxOffsetLength;
var offsetSize = boxBarWidth;
offset('#scroll-item', 'left', offsetSize + 'px');
$interval(function(){
// 获取文本节点的长度
scrollBarWidth = $('#scroll-item').width();
// 最大偏移距离
// maxOffsetLength = scrollBarWidth + boxBarWidth;
// console.log('boxBarWidth', boxBarWidth);
// console.log('maxOffsetLength', maxOffsetLength);
// console.log('offsetSize', offsetSize);
// 判断当前是否超出最大偏移量, 如果超出重置偏移距离
// console.log(offsetSize + scrollBarWidth);
if (offsetSize + scrollBarWidth <= 0) {
offsetSize = boxBarWidth
}
// 在当前偏移量下继续偏移一定距离
offsetSize -= 2;
offset('#scroll-item', 'left', offsetSize + 'px');
},50)
}
}]);