原理:不停地调用定时器,达到在很短的时间(最小执行时间 OSX:10ms,Windows:15ms)移动很短的距离(1px),即视觉上是匀速移动
效果:消息从右往左匀速移动
html(消息内容从后台接口获取然后添加到<ul></ul>中)
<div class="notify" id="js-notify">
<div class="notify-wrap" id="js-notify-wrap">
<ul class="scroll_notify">
</ul>
</div>
</div>
scss
.header{
width: 100%;
position: fixed;
z-index: 99;
.notify-box{
height: 40px;
background: #333;
.notify{
margin: 0 30px;
overflow: hidden;
.notify-wrap{
overflow: hidden;
}
ul{
width: 100%;
float: left;
overflow: hidden;
li{
float: left;
line-height: 40px;
font-size: 14px;
color: #999;
//padding-right: 30px;
//word-break:keep-all;
//white-space:nowrap;
overflow:hidden;
//text-overflow:ellipsis;
span{
font-size: 14px;
line-height: 40px;
font-weight: bold;
margin-right: 3px;
}
}
}
}
}
}
js
getNameList();
//获取报名的用户名和团队名
function getNameList(){
$.ajax({
url:API.getUserNameAndTeamName,
type:"get",
}).done(function(res){
if(res.ok ){
if(res.result&& res.result.length > 0){
notifyScroll(res.result);
}
}else{
Util.alertMessage(res.errorMessage ||'出错啦!');
}
});
}
//Desc: 消息滚动显示
function notifyScroll(result){
var $scrollWrap = $("#js-notify .scroll_notify"), $innerWrap = $("#js-notify-wrap"), html = '';
(result || []).forEach(function(item, i){
html += '<li><span>·</span>'+item.name+'已提交报名,并加入了"'+item.teamName+'"团队!</li>';
});
$scrollWrap.html(html);
var $li = $scrollWrap.find('li');
var maxWidth = 0;
var outerWidth = $("#js-notify").width();
$li.each(function (item, idx) {
var $this = $(this), width = $this.width()+30;//避免maxWidth计算不准确
$this.css('width', width);
maxWidth += width;
});
//不滚动
if(maxWidth <= outerWidth) {
return;
}
var moveWidth = 0;
$("#js-notify .scroll_notify").css("width",maxWidth); //设置滚动盒子宽度
var cloneScroll = $scrollWrap.clone();
$innerWrap.append(cloneScroll).width(maxWidth * 2);
//滚动
function _play() {
moveWidth += 1;
if(moveWidth >= maxWidth) {
moveWidth = 0;
}
$innerWrap.css('marginLeft', -moveWidth);
setTimeout(_play, 10);
}
_play();
}