飘动文字2

HTML

<div class="box">
	<div id="box"></div>
	<ul>
		<li>+1</li>
		<li>+1</li>
		<li>+1</li>
		<li>+1</li>
		<li>+1</li>
		<li>+1</li>
	</ul>
</div>

CSS

.box{
	width: 300px;
	height: 50px;
	position: relative;
	border: 1px solid #000000;
	margin: 200px auto 0;
}
#box{
	width: 0;
	height: 50px;
	background: #00B7FF;
	position: absolute;
	left: 0;
	top: 0;
	opacity: 1;
}
ul{
	margin: 0;
	padding: 0;
	width: 100%;
	height: 100%;
	position: absolute;
	left: 0;
	top: 0;
	list-style: none;
}
li{
	width: 50px;
	height: 50px;
	position: absolute;
	left: 0;
	top: 0;
	opacity: 1;
	text-align: center;
	line-height: 50px;
}

JS

var lis=document.getElementsByTagName("li");
var oBox=document.getElementById("box");
var num=0;
var timer=null;
for (var i=0;i<lis.length;i++) {
	lis[i].style.left=i*50+"px";
}
document.onclick=function(){
	//背景颜色变化
	doMove(oBox,10,300,"width",function(){
		setInterval(function(){
			var op=parseFloat(getStyle(oBox,"opacity"))-0.1;
			oBox.style.opacity=op;
		},30)
	});
	clearInterval(timer);
	//文字
	timer=setInterval(function(){
		moTo(lis[num]);
		num++;
		if(num===lis.length){
			clearInterval(timer);
			num=0;
		}
	},100)
}


function moTo(obj){
	clearInterval(obj.timer);
	obj.timer=setInterval(function(){
		var le=parseInt(getStyle(obj,"left"))-10;
		var tp=parseInt(getStyle(obj,"top"))-10;
		var op=parseFloat(getStyle(obj,"opacity"))-0.06;
		if(le<-50){
			clearInterval(obj.timer);
			le=-50;
			op=0;
			tp=-50
		}
		obj.style.left=le+"px";
		obj.style.top=tp+"px";
		obj.style.opacity=op;
	},30)
}

function doMove(obj,dir,target,attr,endFn){
	dir=parseInt(getStyle(obj,attr))<target?dir:-dir;
				
	clearInterval(obj.timer);
	obj.timer=setInterval(function(){
		var speed=parseInt(getStyle(obj,attr))+dir;//步长
					
		if(speed<target&&dir<0||speed>target&&dir>0){//往后跑
			speed=target;
		}
					
		obj.style[attr]=speed+"px";
					
		if(speed==target){
			clearInterval(obj.timer);
						
//			if(endFn){
//				endFn();
//			}
			endFn&&endFn();
		}
	},30)
}

//获取元素样式函数
function getStyle(obj,attr){
	if(obj.currentStyle){
		return obj.currentStyle[attr];
	}else{
		return getComputedStyle(obj,false)[attr];
	}
}

  

posted @ 2017-11-20 11:34  carol72  阅读(122)  评论(0编辑  收藏  举报