如何制作幻灯片停止

时间:2014-05-20 07:49:45

标签: javascript html

我在javascript中获得了一个幻灯片显示,但是我无法阻止它...任何人都可以建议停止幻灯片放映的最佳方式。以下是html和javascript的代码

<!doctype html>

<html lang="en">
<head>
    <title>Picture Show</title>
    <link type="text/css" rel="stylesheet" href="stylesheet.css" />
    <script type="text/javascript" src="slideshow.js"></script>
</head>
<body>
    <!-- Insert your content here -->
    <div id="container">
        <div id="header">
            <h1>Slide Show</h1>
            <a href="javascript:slideShow()">Start</a>
            <a href="javascript:stopShow()">Stop</a>
        </div>
        <div id="slideShow">
            <img name="image" alt="Slide Show" src="pics/0.jpg" />
        </div>
    </div>
</body>
</html>

javascript文件

//javascript code for slideshow

//pictures
var imgs = [ "pics\/0.jpg", "pics\/1.jpg", "pics\/2.jpg", "pics\/3.jpg", "pics\/4.jpg", "pics\/5.jpg" ];
var imgNum = 0;
var imgsLength = imgs.length-1;

//changing images function
function changeImg(n) {    
    imgNum += n;

    //last position of array
    if (imgNum > imgsLength) {
        imgNum = 0;
    }

    //first position of array
    if (imgNum < 0) {
        imgNum = imgsLength;
    }

    //console.log(images.tagName);
    document.image.src = imgs[imgNum];

    return false;
}

//slideshow function
function slideShow() {
    //slideshow function
    setInterval("changeImg(1)", 2000);
}

//stopping slideshow function
function stopShow() {
    console.log(imgs[imgNum]);
    document.image.src = imgs[imgNum];
}

//window.addEventListener('load', slideShow);

1 个答案:

答案 0 :(得分:0)

更改此功能,可能会有效。

//make the myVar variable global so all functions can reach it.
var myVar = null;

//slideshow function
function slideShow() {
    //slideshow function
    //use the globally defined myVar variable to bind to the interval.
    myVar = setInterval("changeImg(1)", 2000);
}

//stopping slideshow function
function stopShow() {
    clearInterval(myVar);  // This clears the interval
    console.log(imgs[imgNum]);
    document.image.src = imgs[imgNum];
}