在app或者网站的首页我们通常都可以看到一行滚动的网站公告或者资讯消息,每隔几秒就向上无缝滚动一条,一直循环滚动下去,那么这种效果怎么实现呢
实现代码:
可以直接拷贝运行看效果,默认是jQuery调用效果,可以注释切换看js效果
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>公告新闻消息间隔滚动</title>
</head>
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
hot-news{
height: 30px;
line-height: 30px;
width: 400px;
border: 1px solid #ccc;
overflow: hidden;
list-style: none;
}
hot-news a {
font-size: 16px;
color: #666;
text-decoration: none;
}
</style>
<body>
<div id="hot-news"></div>
<script type="text/javascript">
var data = [
{'link':'http://www.xx.com/news/1.html','title':'好消息11,好消息,不容错过的消息'},
{'link':'http://www.xx.com/news/1.html','title':'好消息22,好消息,不容错过的消息'},
{'link':'http://www.xx.com/news/1.html','title':'好消息33,好消息,不容错过的消息'}];
var myScroll = null;
var hotNewEle = document.getElementById("hot-news");
hotNewEle.scrollTop=0;
(function(){
if(data && data.length > 0){
var li = [];
for(var i=0,j=data.length; i < j; i++){
li.push('<li><a href="'+data[i].link+'">'+data[i].title+'</a></li>');
}
hotNewEle.innerHTML = '<ul>'+li.join('')+'</ul>';
// 原生js调用方法
//hotNewEle.innerHTML+=hotNewEle.innerHTML;
//setTimeout(startScroll,2000);
// jQuery调用方法
$("#hot-news ul").append($("#hot-news ul").find("li:eq(0)").clone());
myScroll = setInterval(scroll,2000);
}else{
hotNewEle.style.display = 'none';
}
/*jquery方法*/
var num = 1;
var _ele = $("#hot-news ul");
var sum = _ele.find("li").length;
function scroll(){
_ele.animate({"margin-top":-30*num+"px"},function(){
if(num == sum-1){
num = 1;
_ele.css("margin-top","0px");
}else{
num++;
}
});
}
})();
function startScroll(){
myScroll=setInterval("scrollUp()",50);
hotNewEle.scrollTop++;
}
function scrollUp(){
if(hotNewEle.scrollTop % 30 == 0){
clearInterval(myScroll);
setTimeout(startScroll,2000);
}else{
hotNewEle.scrollTop++;
if(hotNewEle.scrollTop >= hotNewEle.scrollHeight/2){
hotNewEle.scrollTop =0;
}
}
}
</script>
</body>
</html>
网友评论