JavaScript to make a fast-running image slideshow?

I am making an image slideshow using native JS.
I decided to make it myself because it needs to run at ~100ms intervals, and without any special transition effects (see it [here][1]), so I figured it was unnecessary to include a big library like JQuery just for just a simple application.
This is the code I am currently using [edit: original code - now modified]:
// JavaScript Document function preloadimages(arr){ // the preloadimages() function is adapted from var newimages = [], loadedimages = 0; var postaction = function() {}; var arr = (typeof arr != "object") ? [arr] : arr; function imageloadpost() { loadedimages++; if (loadedimages == arr.length) { postaction(newimages); //call postaction and pass in newimages array as parameter } } for (var i = 0; i < arr.length; i++) { newimages[i] = new Image(); newimages[i].src = arr[i]; newimages[i].onload = function() { imageloadpost(); } newimages[i].onerror = function() { imageloadpost(); } } return { //return blank object with done() method done: function(f) { postaction = f || postaction; //remember user defined callback functions to be called when images load } } } /* USAGE: preloadimages(['ed.jpg', 'fei.jpg', 'budapest.gif', 'duck.jpg']).done(function(images) { images.sort(function(a, b) { return a.width - b.width; //sort images by each image's width property, ascending }); alert(images[0].src); //alerts the src of the smallest image width wise }); */ function animateSlideshow() { var num = window.imgNum + 1 ; if (num >= d['imgs'].length) { num = 0; } window.imgNum = num; imgTag.src = d['imgs'][num]; var t = window.setTimeout(function(){animateSlideshow(imgNum, imgTag, d)}, 100); } var d; var imgTag; var imgNum = 0; $.onDomReady (function () { // This is not JQuery, it's a simple cross-browser library which you can read here:$.js // data is an array that should be already defined on the calling page, // containing all the necessary information to generate all the rotation slideshows on the page for (i = 0; i < data.length; i++) { d = data[i]; var div = document.getElementById(d['id']); imgTag = $.Elements.getElementsByClassName('theImage', div)[0]; // preload the images... preloadimages(d['imgs']).done(function(images) { imgTag.src = d['imgs'][0]; animateSlideshow(); }); } });

... HTML document ...

This is what the tag the initial image is in looks like:

Now for the question: this script only allows me to have one single 'slideshow' on the page - because in each iteration of the loop it overrides the `imgNum` variable. Is there an other, better way of doing this slideshow (if possible without JQuery, otherwise OK), even in a completely different way? Thank you EDIT: I have remade the script following Jared Farrish's answer and it's now working fine! [1]:

以上就是JavaScript to make a fast-running image slideshow?的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准