javascript无缝水平滚动实例

首先看源代码:

<html>
<head>
<title>无缝滚动实例--左右滚动</title>
<style type="text/css">
img { border:none; margin:0px; }
#demo { width:600px; overflow:hidden; height:120px; border:solid 3px red; }
#demo1 { float:left; width:766px; }
#demo2 { float:left; width:766px; }

#clear { clear:both; }
</style>
</head>

<body>
<div id="demo">
<div id="marquee">
   <div id="demo1">
    <img src="images/js01.jpg" width="120" height="120" />
    <img src="images/js02.jpg" width="120" height="120" />
    <img src="images/js03.jpg" width="120" height="120" />
    <img src="images/js04.jpg" width="120" height="120" />
    <img src="images/js05.jpg" width="120" height="120" />
    <img src="images/js06.jpg" width="120" height="120" />
   </div>

   <div id="demo2"></div>
</div>
</div>

<div id="clear">&nbsp;</div>

<script type="text/javascript">
var speed = 10;
var demo = document.getElementById("demo");
var demo1= document.getElementById("demo1");
var demo2= document.getElementById("demo2");
var marquee = document.getElementById("marquee");

demo2.innerHTML = demo1.innerHTML;
marquee.style.width = demo1.offsetWidth * 2;
function fMarquee()
{
if(demo2.offsetWidth - demo.scrollLeft <= 0) { demo.scrollLeft -= demo2.offsetWidth; }
else { demo.scrollLeft++; }
}

var myMarquee = setInterval(fMarquee,speed);
demo.onmouseover = function() { clearInterval(myMarquee); }
demo.onmouseout = function() { myMarquee = setInterval(fMarquee, speed); }
</script>
</body>

</html>

 

代码结束。

 

基本原理与垂直滚动效果是一样的,只不过,在布局的时候发生了一点小小的改变。

他的结构应该是这样的

<div id="demo">
<div id="marquee">
    <div id="demo1">
      content...
    </div>
    <div id="demo2"></div>
</div>
</div>

 

用demo包含所有的内容。而且demo必须制定宽度和高度,且overflow:hidden;必须加上。其实demo指定的是滚动框的高度和宽度。

用marquee包含所有的内容,与demo不同的是,marquee的宽度是刚好够放下demo1与demo2的内容的(横向排列,所以需要float:left; 而且宽度要设置。)

接下来的是用javascript将marquee的宽度设置为两倍demo1的宽度。marquee.style.width = demo1.offsetWidth * 2; 以确保demo1与demo2是横向排列的。

在滚动时,若demo的scrollLeft已经到超过了demo2的宽度,说明应该重新开始了。用

if(demo2.offsetWidth - demo.scrollLeft <= 0) { demo.scrollLeft -= demo2.offsetWidth; }
else { demo.scrollLeft++; }

最后用var myMarquee = setInterval(fMarquee, speed) 重复滚动。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值