HTML5+js的两种轮播图(静态获取图片方法和动态获取图片)

来源:互联网 发布:餐饮订餐软件 编辑:程序博客网 时间:2024/06/05 14:32
第一种:静态获取图片写法,给定图片的个数,用js实现轮播图自动转换。
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><!-- *******设置样式********** --><style type="text/css">.show_div{width: 400px;height: 400px;margin:  0 auto;border: 2px solid block;overflow: hidden;}.scroll_div{width: 2000px;height: 400px;}.scroll_div img{width: 400px;height: 400px;float: left;}</style><!-- end --></head><body><div class="show_div"><div class="scroll_div"><img src="img/b.jpg" alt=""><img src="img/c.jpg" alt=""><img src="img/d.jpg" alt=""><img src="img/a.jpg" alt=""><img src="img/b.jpg" alt=""></div></div></body><!-- *********js代码******** --><script type="text/javascript">var scrollDiv = document.getElementsByClassName("scroll_div")[0];// 定义初始值var left =0;// 定义一个定时器 走一步 function move(){var timer = setInterval(function(){left --;if (left <= -1600) {left = 0;}if (left % -400 == 0) {clearInterval(timer);timer = null;}scrollDiv.style.marginLeft = left + "px";},10);}// 定义一个定时器 每隔固定时间 走一张setInterval(function(){move();},5000);</script></html>

第二种:动态获取图片写法。在js块中写入存放图片和相关数据的数组,然后通过拼接字符串的方式展示到页面中,然后设置相关的样式

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><link rel="shortcut icon" href="img/title.jpg" type="image/png"><title>jsan版轮播图</title><style type="text/css">*{padding: 0;margin:0;}.show_div{width: 400px;height: 400px;border: 2px solid black;overflow: hidden;margin: 0 auto;}.scroll_div{height: 400px;position: relative;}.scroll_div div{width: 400px;height: 400px;background-color: cyan;float: left;}.scroll_div p{width: 400px;height: 30px;position: absolute;bottom: 0;background-color: black;opacity: 0.7;font-size: 20px;color: white;text-align: center;}.scroll_div img{width: 400px;height: 400px;float: left;}</style></head><body><div class="show_div"><div class="scroll_div"></div></div></body><script type="text/javascript">var showDiv = document.getElementsByClassName("show_div");var scrollDiv = document.getElementsByClassName("scroll_div")[0];/*数组*/var data = [{url:"img/z3.jpg",title:'张杰1'},{url:"img/z4.jpg",title:"张杰2"},{url:"img/z5.jpg",title:"张杰3"},{url:"img/z6.jpg",title:"张杰4"}];scrollDiv.style.width = 400 * (data.length+1)+"px";for (var i = 0; i < data.length; i++) {/*创建div,并放进父级元素下面*/var myDiv = document.createElement('div');scrollDiv.appendChild(myDiv);myDiv.innerHTML = '<p>'+data[i].title+'</p>'+'<img src = "'+data[i].url+'">';}/*轮播图代码 和第一种代码原理相同,*/var left = 0;setInterval(function(){move();},5000);function move(){var timer = setInterval(function(){left -- ;if (left % -400 == 0) {clearInterval(timer);}if (left == -1200) {left = 0;}scrollDiv.style.marginLeft = left +"px";},10);}</script></html>


原创粉丝点击