如何将setTimeout()与slow函数一起使用

How to use setTimeout() with slow function

本文关键字:函数 slow 一起 setTimeout      更新时间:2023-09-26

在w3school中(试试看)我有这样的代码:

<!DOCTYPE html>
<html>
<body>
<img name="slide" class="slider" src="" width="400"/>
<script>
var i = 0;
var path = new Array();
path[0] = "http://vignette2.wikia.nocookie.net/batman/images/9/92/Batman-ArkhamKnight-BatsuitRender.png/revision/latest?cb=20140605151444";
path[1] = "http://vignette4.wikia.nocookie.net/injusticegodsamongus/images/c/c5/BATGIRL.png/revision/latest?cb=20130527034044";
path[2] = "http://vignette2.wikia.nocookie.net/injusticegodsamongus/images/b/bb/Raven_Render.png/revision/latest?cb=20130318184222";
path[3] = "http://vignette1.wikia.nocookie.net/injusticegodsamongus/images/7/7f/ARES.png/revision/latest?cb=20130411230035";
function swapImage() {
    document.slide.src = path[i];
    if (i < path.length - 1)
        i++;
    else 
        i = 0;
    setTimeout("swapImage()", 2000);
}
window.onload = swapImage;
</script>
</body>
</html>

所以我尝试使用setTimeout函数,它是有效的,但有可能改变这些图像slow()吗?

如果您想更改图片显示的持续时间,您应该将setTimeout的第二个参数从2000更改为所需时间(以毫秒为单位)。

要在图像交换中使用不同的效果,您应该将document.slide.src = path[i];行更改为其他内容,这取决于您试图调用的效果类型。试着使用jQuery,它有很多开箱即用的好效果,但你也可以使用css。互联网上有很多解释得很好的方法,所以研究一下,找到自己的方法。

当你说更改它"慢"时,这意味着具有淡入淡出效果吗?您可以使用jQuery来做到这一点。

http://api.jquery.com/fadeout/

http://api.jquery.com/fadein/

在您的示例中,更改

<!DOCTYPE html>
<html>
<body>
<img name="slide" class="slider" src="" width="400"/>
...
function swapImage() {
    document.slide.src = path[i];
    if (i < path.length - 1) i++;
    else i = 0;
    setTimeout("swapImage()", 2000);
 }

<!DOCTYPE html>
<html>
<body>
<img name="slide1" class="slider" style="display:none;" src="" width="400"/>
<img name="slide2" class="slider" src="" width="400"/>
...

var current = document.slide1;
var next = document.slide2;
function swapImage() {
    var swap;
    current.src = path[i];
    next.src = path[i+1];
    if (i < path.length - 1) i++;
    else i = 0;
    jQuery(current).fadeOut();
    jQuery(next).fadeIn();
    swap = current;
    current = next;
    next = swap;
    setTimeout(swapImage, 2000);
 }

但事实上,使用jQuery和其他助手函数会对您有很大帮助。