<style type="text/css">
*{
margin:0;
padding:0;
}
.rota-img{
width:650px;
height:350px;
position:absolute;
top:0;right:0;bottom:0;left:0;
margin:auto;
}
.rota-img button:nth-child(2){
position:absolute;
top:0;bottom:0;
margin:auto 0;
left:0;
width:40px;
height:40px;
font-size:30px;
}
.rota-img button:nth-child(3){
width:40px;
height:40px;
position:absolute;
top:0;bottom:0;
margin:auto 0;
right:0;
font-size:30px;
}
.rota-img img{
width:650px;
height:350px;
}
</style>
</head>
<body>
<div class="rota-img">
<img src="1.jpg" id="rotaImg" class="imgs">
<button onclick="goPre()"><</button>
<button onclick="goNext()">></button>
</div>
<script type="text/javascript">
var arr = ["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg"];
var timer;
var inx = 0;
function autoRotate(){
document.getElementById("rotaImg").src = arr[inx];
if(inx == 4){
inx = 0;
}else{
inx++;
}
timer = setTimeout(autoRotate,2000);
}
autoRotate();
function goNext(){
clearTimeout(timer);
document.getElementById("rotaImg").src = arr[(inx+1)];
autoRotate();
}
function goPre(){
clearTimeout(timer);
document.getElementById("rotaImg").src = arr[(inx-1)];
autoRotate();
}
</script>
https://blog.csdn.net/qiladuo1207/article/details/81365777
var arr = ["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg"];
var timer;
var inx = 0;
var len = arr.length;//获取长度
function autoRotate(is) {
if(inx == 0 && !is){
inx = len;
}else if(inx == len+1 && is){
inx = 1;
}else if(inx == len && is){
inx = 0;
}else if(inx == 1 && !is){
inx = len+1;
}
is ? inx++ : inx--;
document.getElementById("rotaImg").src = arr[inx-1];
if (inx == len && is) {
inx = 0;
}else if (inx == 1 && !is) {
inx = len+1;
}
timer = setTimeout(_ => autoRotate(is), 5000);
}
autoRotate(true);
function goNext() {
clearTimeout(timer);
autoRotate(true);
}
function goPre() {
clearTimeout(timer);
autoRotate(false);
}
因为你两个按钮的点击事件里面前两句完全没用,他们虽然临时改变了图片路径但下一步就执行你的autoRotate();方法了,这个方法不受你点击事件的影响。我的建议是做个全局变量,存储你这里的inx,点击按钮时候清除计时器,然后改变inx的值,并在一定的时间后再重新开始执行计时器(计时器中只做inx的累加,判断,不去赋初值)。并且我在这不建议你频繁改图片路径,我建议你写页面时候一个div放一个图片,div做绝对定位,然后JS控制div的显示、隐藏,效果可能更好