如何在HTML中每15秒更改一个图像



我有一个图像在我的HTML页面,我希望它改变为不同的图像每15秒。

<img src="img/img 1.jpg" alt="image">

在我的本地文件夹img中,我有两个图像是img 1.jpgimg 2.jpg。如何在15秒后将img 1.jpg更改为img 2.jpg ?

试一试:

$(document).ready(function(){
    var img = 0;
    var slides = new Array();
    while (img < 5) {
        img++;
        // put your image src in sequence
        var src = 'assets/images/earth/Sequence' + img + '.jpg';
        slides.push(src);
    }
    var index = 0,timer = 0;
    showNextSlide();
    timer = setInterval(showNextSlide, 15000);
    function showNextSlide() {
        if (index >= slides.length) {
            index = 0;
        }
        document.getElementById('earth').src = slides[index++];
    }
});

试试这个(纯JS)

var myArray = ['img1', 'img2', 'img3', 'img4', 'img5', 'img6']
var count = 0;
setInterval(function() {
  //use this below line if you want random images
  //var rand = myArray[Math.floor(Math.random() * myArray.length)];
  if (count >= myArray.length) count = 0; // if it is last image then show the first image.
  // use this below line if you want images in order.
  var rand = myArray[count];
  document.getElementById('img').src = rand;
  document.getElementById('img').alt = rand; // use 'alt' to display the image name if image is not found
  count++;
}, 1000); // 1000 = 1 second
<img src="img/img 1.jpg" alt="image" id='img' />

要做到这一点,您将需要一些Javascript来更改图像。这里有一个链接到一个流行的网站,可以帮助你学习Javascript、HTML、CSS和更多的东西。你需要特别关注的是这个页面上的setInterval()函数:http://www.w3schools.com/js/js_timing.asp

如果你根本不懂Javascript,这也是一个不错的开始学习的地方!如果这就是您所需要的,那么您只需要很少的Javascript。

  1. 首先在你的页面中包含jQuery库

  2. 然后使用下面的脚本:

    $(document).ready(function() {
        setInterval(function(){
            _path = $('img').attr('src');
            _img_id = _path.replace('img/img', '');
            _img_id = _img_id.replace('.jpg', '');
            _img_id++;
            if (_img_id == 3) {
                _img_id = 1;
            };
            $('img').attr('src', 'img/img' + _img_id + '.jpg');
        }, 15000);
    });
    

最新更新