如何使用js實現圖片輪播
阿新 • • 發佈:2019-02-18
要說起js的輪播功能,已經是有很多成熟的方法,在這裡,這個演算法確實好:
看看下面的程式碼實現吧:
在上面程式碼中,主要的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>
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,然後根據長度進行控制顯示與否