gpt4 book ai didi

javascript递归地改变图像

转载 作者:行者123 更新时间:2023-12-03 16:36:05 25 4
gpt4 key购买 nike

我正在尝试使用 javascript 递归函数在我的网站上以延迟方式递归更改图像。这是我的 js 代码:

    const ns = 0;
carousel(ns);

function carousel(n) {
if(n < 0 || n > 3){
n = 0;
}
var x = document.getElementsByClassName("cooperation-ovalImg");
x[0].src = "Images/cooperation/Oval_1.1.png";
x[1].src = "Images/cooperation/Oval_2.1.png";
x[2].src = "Images/cooperation/Oval_3.1.png";
n++;
if (n > x.length) {n = 1}
x[n-1].src = "Images/cooperation/Oval_"+n+".png";
setTimeout(carousel(n), 5000); // Change image every 2 seconds
}
    <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/main.css">
<link rel="stylesheet" type="text/css" href="css/test-header.css">
<link rel="stylesheet" type="text/css" href="css/about-us.css">
<link rel="stylesheet" type="text/css" href="css/our-projects.css">
<link rel="stylesheet" type="text/css" href="css/cooperation.css">
<title>Pecode Software | IT company</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</head >


<div class="row row-14">
<div class="col-xs-10 col-xs-offset-2">
<img class="cooperation-ovalImg cooperation-ovalImg-1 cooperation-oval-1" src="Images/cooperation/Oval_1.1.png" alt="">
<img class="cooperation_line" src="Images/cooperation/Lin.svg" alt="">
<img class= "cooperation-ovalImg cooperation-oval-2" src="Images/cooperation/Oval_2.1.png" alt="">
<img class="cooperation_line" src="Images/cooperation/Lin.svg" alt="">
<img class= "cooperation-ovalImg cooperation-oval-3" src="Images/cooperation/Oval_3.1.png" alt="">
</div>
</div>

我采用n参数,因为我希望将来除了自动更改之外还可以通过点击更改图像。

但是有一个问题:环境告诉我:

Function 'carousel' runs recursively infinite, and can only end by throwing an exception

当我运行页面时,脚本不起作用;显示 3 中的第 1 个图像,并且正在改变点。

最佳答案

您应该使用 interval而不是超时。您的环境告诉您,无法退出该功能。这是不好的做法。

你应该使用这样的东西:

var myinterval;

myinterval = setInterval(function(){
// myFunction(params)
}, 5000);

function myFunction(params){
// Your stuff in here
}

// To exit or finish your stuff you will call
/* clearInterval(myinterval); */

关于javascript递归地改变图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52589021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com