ちょっと余計なこと
<!DOCTYPE html> <html> <meta charset="utf-8"> <title>スライドショー</title> <body> <p> <img src="a1.jpg" id="Ga" alt="images"> もし違うタイミングで複数の箇所の画像を替えたいとしたなら? <script> function Changer (target, speed, imgs) { this.target = target; this.speed = speed; this.imgs = imgs; this.timerId = null; this.index = 0; } Changer.prototype.start = function (){ var that = this; var cbFunc = function () { that.show (); }; if (! this.timerId) this.timerId = setInterval (cbFunc, this.speed); return this; } /* Changer.prototype.stop = function () { if (this.timerId) this.timerId = clearInterval (this.timerId), null; return this; }; */ Changer.prototype.show = function () { if (this.index === this.imgs.length) this.index = 0; this.target.src = this.imgs[this.index++]; return this; }; //__ var ga = new Changer ( document.getElementById ('Ga'), 1000, ['a1.jpg','a2.jpg','a3.jpg','a4.jpg','a5.jpg'] ); ga.start (); // (new Changer (id,200,[ary0,ary1,..])).start (); </script>
ほぼ同じこと
function Changer (target, speed, imgs) { var timerId = null; var index = 0; var obj = { start: function () { if (! timerId) timerId = setInterval (obj.show, speed); }, stop: function () { if (timerId) timerId = clearInterval (timerId), null; }, show: function () { if (index === imgs.length) index = 0; target.src = imgs[index++]; } }; return obj; }
関数に引数を渡す方法には2種類あって、
hoge (123,"abc"); //通常
hoge.call (obj, 123, "abc"); //オブジェクトを渡す this===obj
画像の交換を途中で止めたければ
<input type="button" value="Stop" onclick="ga1.stop()">
再開は
<input type="button" value="Start" onclick="ga1.start()">
それぞれで止められる。
もしプログラムが複雑になってくると…