要说起js的轮播功能,已经是有很多成熟的方法,在这里,这个算法确实好:
看看下面的代码实现吧:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>爱你,我的星星</title>
</head>
<script>
window.onload = function(){
var images = document.getElementsByTagName('img');
var pos = 0;
var len = images.length;
setInterval(function(){
images[pos].style.display = 'none';
pos = ++pos == len ? 0 : pos;
images[pos].style.display = '';
images[pos].style.width = '100%';
images[pos].style.height = '600px';
},4000);
};
var flag =true;
function sayLove(says){
console.log(("Love you"));
var word = document.getElementById('word');
word.innerHTML='Love you';
if(flag){
word.style.fontSize= 250+"px";
word.style.color= "#ff6699";
flag=false;
}
else{
word.style.fontSize= 100+"px";
word.style.color= "#ff33ff";
flag=true;
}
}
setInterval(sayLove,2000);
</script>
<style>
p{
width: 100%;
height: auto;
text-align: center;
vertical-align: middle;
font-family: "Leelawadee UI";
font-size: 200px;
color: red;
}
img{
width: 100%;
height: 600px;
}
</style>
<body>
<div id="img1">
<img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496516612428&di=c816521ad939a3e4dcd650884924b75b&imgtype=0&src=http%3A%2F%2Fpic.58pic.com%2F58pic%2F12%2F46%2F01%2F44U58PICadB.jpg">
</div>
<div id="img2">
<img src="https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1496505469&di=01174428c628d94d715dab35aa723aa4&src=http://pic.58pic.com/58pic/14/34/32/67G58PICJx3_1024.jpg">
</div>
<div id="img3">
<img src="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=558345718,1618495907&fm=23&gp=0.jpg">
</div>
<div id="img4">
<img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496516612425&di=9c68ca807a96e785c5ddef17f7dfc194&imgtype=0&src=http%3A%2F%2Fimg.sccnn.com%2Fbimg%2F338%2F27909.jpg">
</div>
<p style="float: left" id="word"></p>
</body>
</html>
在上面代码中,主要的js为下面内容:
window.onload = function(){
var images = document.getElementsByTagName('img');
var pos = 0;
var len = images.length;
setInterval(function(){
images[pos].style.display = 'none';
pos = ++pos == len ? 0 : pos;
images[pos].style.display = '';
images[pos].style.width = '100%';
images[pos].style.height = '600px';
},4000);
};
就这段简单的代码实现了图片的轮播,其实现思路是获取所有的img,然后根据长度进行控制显示与否