一、Html布局
<body>
<div id="rollInfo">
<div id="item"><h3>无缝滚动</h3></div>
<div id="infoText">
<ul id="con1">
<li>1、学会HTML5</li>
<li>2、学会CSS3</li>
<li>3、学会写原生Js</li>
<li>4、学会使用Jquery</li>
<li>5、学会使用bootstarp</li>
<li>6、学会Augular</li>
<li>7、学会Node</li>
<li>8、学会React</li>
<li>9、学会Vue</li>
</ul>
<ul id="con2"></ul>
</div>
</div>
</body>
二、Css样式
<style>
body,h3,ul{
margin:0;
padding: 0;
}
ul{
list-style: none;
}
#rollInfo{
width: 400px;
height: 300px;
margin:0 auto;
margin-top: 30px;
border: 1px solid #ccc;
border-radius: 5px;
}
#item{
width: 100%;
height: 100px;
background: pink;
border: 2px solid #ddd;
text-align: center;
}
#item h3{
display: inline-block;
margin:10% 0px;
}
#infoText{
text-align: center;
background: #e3c06e;
height:200px;
width: 100%;
overflow: hidden;
/*超出部分隐藏 一定要加*/
}
#infoText li{
height: 40px;
/*单条信息的高度*/
}
</style>
三、Js部分
<script>
window.onload = function(){
var area = document.getElementById("infoText");
var con1 = document.getElementById("con1");
var con2 = document.getElementById("con2");
//要实现无缝滚动 必须clone一份滚动的内容
con2.innerHTML = con1.innerHTML;
function scrollUp(){
if(area.scrollTop >= con1.offsetHeight){
area.scrollTop = 0;
}else{
area.scrollTop++;
}
}
var myScroll =setInterval(scrollUp,50);
//鼠标悬停
area.onmouseover = function(){
clearInterval(myScroll);
}
area.onmouseout = function(){
myScroll =setInterval(scrollUp,50);
//不能再使用 var myScroll 定义setInterval
//这样每次移出都会打开新的定时器
}
}
</script>
<script>
window.onload = function(){
var area = document.getElementById("infoText");
var con1 = document.getElementById("con1");
var con2 = document.getElementById("con2");
con2.innerHTML = con1.innerHTML;
要实现无缝滚动 必须clone一份滚动的内容
area.scrollTop = 0;
var iLiHeight = 40;//滚动距离 目前等于单条信息高度
var speed = 50;//滚动速度
var delay = 2000;//滚动的间歇时间
var timer;
function startMove(){
area.scrollTop++;
timer =setInterval(scrollUp,speed);
}
function scrollUp(){
if(area.scrollTop%iLiHeight == 0){
//如果滚动高度等于信息高度的整数倍
clearInterval(timer);
setTimeout(startMove,delay);
}else{
area.scrollTop++;
if(area.scrollTop >= area.scrollHeight/2){
//area.scrollHeight/2的值等于con1.offsetHeight
area.scrollTop = 0;
}
}
}
setTimeout(startMove,delay);//初始化
}
</script>