JavaScript代码实现图片循环滚动效果
1.概述
循环滚动图片,不仅可以增添Web页面的动态效果,而且可以节省页面空间,有效地保证在有限的页面中显示更多的图片。
2.技术要点
主要应用setTimeout()方法实现图片的循环滚动效果。setTimeout()方法的语法格式如下:
setTimeout(function,milliseconds,[arguments])
参数说明:
a.function:要调用的JavaScript自定义函数名称。
b.Milliseconds:设置超时时间(以毫秒为单位)。
功能:经过超时时间后,调用函数。此值可以用clearTimeout()函数清除。
3.具体实现
(1)在页面的合适位置添加一个id属性为demo的<div>标记,并在该标记中添加表格及要要滚动显示的图片。关键代码如下:
<divid="demo"style="overflow:hidden;width:455px;height:166px;">
<tableborder="0"cellspacing="0"cellpadding="0">
<tr>
<tdvalign="top"id="marquePic1">
<!--要循环滚动的图片-->
<tablewidth="455"border="0"align="center"cellpadding="0"cellspacing="0">
<tralign="center">
<%for(inti=1;i<8;i++){%>
<td><imgsrc="Images/<%=i%>.jpg"width="118"height="166"border="1"></td>
<%}%>
</tr>
</table>
</td>
<tdid="marquePic2"width="1"></td>
</tr>
</table>
</div>
(2)编写自定义的JavaScript函数move(),用于实现无间断的图片循环滚动效果。speed数值越大图片滚动的越快,具体代码如下:
<scriptlanguage="javascript">
varspeed=30;//设置间隔时间
marquePic2.innerHTML=marquePic1.innerHTML;
vardemo=document.getElementById("demo");//获取demo对象
functionMarquee(n){//实现图片循环滚动的方法
if(marquePic1.offsetWidth-demo.scrollLeft<=0){
demo.scrollLeft=0;
}
else{
demo.scrollLeft=demo.scrollLeft+n;
}
}
varMyMar=setInterval("Marquee(5)",speed);
demo.onmouseover=function(){//停止滚动
clearInterval(MyMar);
}
demo.onmouseout=function(){//继续滚动
MyMar=setInterval("Marquee(5)",speed);
}
</script>
知识点补充:javascript实现页面的自动循环滚动
首先html代码
<divid="content"> <olid="EG-CN-1">EG-CN-1 <litype="none">aatox</li> <litype="none">akari</li></ol> <olid="EG-CN-10">EG-CN-10<litype="none">rakan</li></ol> <olid="EG-CN-7">EG-CN-7<litype="none">riven</li> <litype="none">darius</li></ol> <olid="EG-CN-8">EG-CN-8<litype="none">fiora</li> <litype="none">jayce</li> <litype="none">noc</li></ol> <olid="EG-CN-2">EG-CN-2<litype="none">leesin</li></ol></div>
这是一个通过js自动添加list的div容器,随着名单的长度增加会自动增加scrollheight,而整个div是固定的宽高,通过css的overflow:scroll属性自动将多出的内容隐藏在scrollview里面
css代码如下,这里同时使用::-webkit-scrollbar将滚动条隐藏以保证美观性
#content{
width:430px;height:490px;
position:absolute;top:180px;left:40%;
font-size:20px;overflow:scroll;
}
#content::-webkit-scrollbar{display:none}
ol{font-size:35px}
li{font-size:25px}
接下来就是实现自动循环滚动的js代码
原理就是先读取div元素的高度以及div内部内容的高度即clientHeight和scrollHeight属性来确定滚动条到顶部的最大距离h=clientHeight-scrollHeight,然后通过setInterval来实现滚动条到顶部的距离scrollTop属性的从0开始递增直到达到最大距离h,然后再将scrollTop归零,重新开始滚动
$(document).ready(function(){
content=document.getElementById('content')
clientheight=content.clientHeight
offsetheight=content.scrollHeight
h=offsetheight-clientheight
varposition=0
functionstartscroll(){
if(content.scrollTop<h){position++;content.scrollTop=position}
if(content.scrollTop>=h){content.scrollTop=0;position=0}
}
setInterval(startscroll,100)
console.log(clientheight)
console.log(offsetheight)
})
总结
以上所述是小编给大家介绍的JavaScript代码实现图片循环滚动效果的相关知识,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!