【问题标题】:Why does the slide of my javascript carousel not reset?为什么我的 javascript carousel 的幻灯片没有重置?
【发布时间】:2014-03-20 00:54:12
【问题描述】:

如果用户不点击任何内容,我有一个轮播,它每 4 秒浏览一次幻灯片。但是,我遇到的问题是,例如,如果用户在 1 秒后单击一张幻灯片,然后在 2 秒后单击下一张,则以下幻灯片不会在 4 秒后出现。 js代码如下:

var arr = [];
arr[0]= new Image();
arr[0].src = "1.jpg";
arr[1]= new Image();
arr[1].src = "2.jpg";
arr[2]= new Image();
arr[2].src = "3.jpg";

titleArray = new Array();
titleArray[0] = "first";
titleArray[1] = "second";
titleArray[2] = "third";

var i=0;

function slide(){
document.getElementById("img1").src= arr[i].src;
document.getElementById("title").innerHTML = titleArray[i];
    i++;
    if(i==arr.length){
        i=0;
    }
setTimeout(function(){ slide(); },4000);
}

html 是:

<!doctype html>
<html lang="en">
<head>
 <title>Carousel</title>

 <link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700'     rel='stylesheet' type='text/css'>
 <link rel="stylesheet" href="style.css">
</head>

<body onLoad="slide();">

<div class="image">
  <img src="1.jpg" width="510" height="390" id="img1">
  <a href="JavaScript:slide(this)">  
<img src="carousel-label-box.png"    id="img2" width="310" height="190"> 
  </a>
  <h1 id="title">first</h1>

 </div>
 <script src="script.js"></script>
</body>
</html>

【问题讨论】:

    标签: javascript html timer carousel slide


    【解决方案1】:

    您的意思是当用户点击图片时,幻灯片会在预期的 4 秒前发生变化?

    据我所知,您应该调用 clearTimeout() 来中断它,然后在用户单击图像而不是简单地调用幻灯片时再次设置它。

    编辑:忘了说当用户点击它时你仍然应该调用 slide() 函数。

    【讨论】:

    • 我刚刚注意到您在函数幻灯片中调用了 setTimeout。这使得每当用户单击图像时,您的 slide() 函数的另一个 Timeout 就会在原始函数之间调用。您应该在函数之外调用 setTimeout。让我知道它是否有效。
    猜你喜欢
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    相关资源
    最近更新 更多