<html> |
<head> |
<title>JS实现跑马灯效果</title> |
<style> |
* { |
font-size:12px; |
font-family:宋体, Arial; |
} /*规定了所有的字体样式*/ |
body { |
overflow:auto; |
} |
#mq { |
width:220px; |
height:40px; |
line-height:20px; |
overflow:hidden; |
border:1px solid black; |
} |
#mq div { |
position:absolute; |
width:220px; |
padding:0px 10px; |
} |
</style> |
<script> |
function init(){ |
initMq($( "mq" )); |
$( "mq" ).start(); |
} |
|
function initMq(obj){ |
var objs; |
//定义跑马灯对象的自定义属性 |
obj.currentItem = -1; |
obj.loopDelay = 50; |
obj.loopItems = new Array(); |
obj.loopTimer = null ; |
obj.speedX = 2; |
obj.speedY = 2; |
//定义跑马灯对象的自定义方法 |
obj.loop = mq_loop; |
obj.start = mq_startLoop; |
obj.stop = mq_stopLoop; |
//定义跑马灯对象的事件 |
obj.onmouseover = function (){ this .stop(); } |
obj.onmouseout = function (){ this .loop(); } |
|
//获取跑马灯对象的所有子元素 |
objs = obj.getElementsByTagName( "div" ); |
for ( var i=0; i<objs.length; i++){ |
//在loopItems属性中记录子元素 |
obj.loopItems.push(objs[i]); |
//自定义子元素的属性和方法 |
objs[i].index = i; |
objs[i].move = move; |
objs[i].reset = mq_reset; |
//初始化子元素的状态 |
objs[i].reset(); |
} |
} |
|
function move(x, y){ |
this .style.left = x + "px" ; |
this .style.top = y + "px" ; |
} |
|
function mq_loop(){ |
var obj; |
clearTimeout( this .loopTimer); |
if ( this .currentItem >= this .loopItems.length) this .currentItem = 0; |
obj = this .loopItems[ this .currentItem]; |
if (obj.offsetLeft!= this .offsetLeft){ |
//向左卷动 |
obj.move(obj.offsetLeft - this .speedX, obj.offsetTop); |
} else if (obj.offsetTop + obj.offsetHeight > this .offsetTop){ |
//向上卷动 |
obj.move(obj.offsetLeft, obj.offsetTop - this .speedX); |
} else { |
//重置该子元素 |
obj.reset(); |
this .currentItem++; |
} |
this .loopTimer = setTimeout( "$(\"" + this .id+ "\").loop();" , this .loopDelay); |
} |
|
function mq_reset(){ |
var p = this .parentNode; |
this .move(p.offsetLeft + p.offsetWidth, p.offsetTop); |
} |
|
function mq_startLoop(){ |
for ( var i=0; i< this .loopItems.length; i++) this .loopItems[i].reset(); |
this .currentItem = 0; |
this .loop(); |
} |
|
function mq_stopLoop(){ |
clearTimeout( this .loopTimer); |
} |
|
function $(str){ return (document.getElementById(str)); } |
window.onload = init; |
</script> |
</head> |
<body> |
<div id= "mq" > |
<div> js实现的跑马灯效果11111 </div> |
<div> js实现的跑马灯效果22222 </div> |
</div> |
</body> |
</html> |
初级程序员
by: 我若安好便是晴天 发表于:2014-05-29 11:57:21 顶(2) | 踩(7) 回复
回复评论