javascript - javascript中如何通过数组实现自动滑动图片

标签 javascript

我想在网站加载后立即实现滑动图像。

这是我的 html 代码

<html>
<title>Wold of Guitars</title>
<body onload="images()">
</body>
</html>

这是我的 JavaScript

var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = '../img/n/h1.jpg';
imgArray[1] = new Image();
imgArray[1].src = '../img/n/h2.jpg';
imgArray[2] = new Image();
imgArray[2].src = '../img/n/home.jpg';
imgArray[3] = new Image();
imgArray[3].src = '../img/n/h3.jpg';
imgArray[4] = new Image();
imgArray[4].src = '../img/n/h4.jpg';
x=-1;
function images()
{    x=x+1
     if(x>4)
     x=1
     document.write("<li><img src='" + imgArray[x] + "' width="1350" height="630"/><span>" + imgArray[] + "</span></li>");
     var t=setInterval("images()",3000);
}

我们将不胜感激。

最佳答案

尽管您提到“滑动”,但您的初始代码看起来像是您想要随着时间的推移交换图像。

我承认,对于如此简单的事情,您可能很难找到有关 JavaScript 的优质资源,这就是为什么我可以理解您的问题。

好的,这是一个快速、肮脏但更现代的图像更改幻灯片 requestAnimationFrame:

https://jsfiddle.net/julienetienne/95tqftnk/4/

相同的原理适用于使图像幻灯片化,只不过您要预先加载所有图像并按幻灯片放映宽度移动位置。

var speed = 3;

// Your image array
var images = [
    'http://www.gettyimages.co.uk/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg',
    'http://www.hdwallpapersimages.com/wp-content/uploads/images/Child-Girl-with-Sunflowers-Images.jpg',
    'http://www.gettyimages.co.uk/CMS/StaticContent/1391099215267_hero2.jpg'];

// Get the slideShow tag
var slideShow = document.getElementById('slide-show');

// Create the image tag  //You could also just make one in HTML and get the tag
var img = document.createElement('img');

// Append the image to the slideshow container
slideShow.appendChild(img);

// Basic request animation polyfill 
var rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
        return setTimeout(callback, 1000 / 60);
    };

// declare var count outside of rAF loop
var count;

function changeImage(timeStamp) {
    count = Math.floor(timeStamp / 1000 / speed);

while (count > images.length -1) {
    count -= images.length;
}

    img.src = images[count];

    rAF(changeImage);
}

rAF(changeImage);
img {
    width: 600px;
    height auto;
}
<div id="slide-show"></div>

关于javascript - javascript中如何通过数组实现自动滑动图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30109044/

相关文章:

javascript - 使用 javascript 控制 css 过渡

javascript - NestJS - 如何提供动态模块的服务

javascript - jquery : Order of execution

减法期间的 Javascript 意外行为

javascript - 如何从 Knockout.js 的复选框列表中只选择一个复选框

javascript - 多个下拉 <select> 菜单,一次只能选择一个

Internet Explorer 上的 Javascript 语法错误

javascript - 如何将 bluebird Promise 应用于我现有的 javascript 遍历和基于递归的逻辑?

javascript - 如何将下一个/上一个按钮添加到 Surface 平板电脑触摸幻灯片?

javascript - Discord.js - 引用错误 : join is not defined