问题
I am creating an image slider and using a JavaScript timer to advance to the next picture. When the user clicks on the forward or back button (see picture below) the time the slide is displayed decreases greatly. I need help making the buttons advance the slide and reset the timer and the same time. I am attaching my JavaScript, HTML, and CSS to cover my code thoroughly.
My JavaScript:
var imageShown = 1;
var total = 7;
function autoplay() {
var image = document.getElementById('picture');
imageShown = imageShown + 1;
if(imageShown > total){imageShown = 1;}
if(imageShown < 1){imageShown = total;}
picture.src = "Images/img"+ imageShown +".jpg";
console.log("Pic Changed");
}
window.setInterval(autoplay, 5000);
function pic(x) {
var image = document.getElementById('picture');
imageShown = imageShown + x;
if(imageShown > total){imageShown = 1;}
if(imageShown < 1){imageShown = total;}
picture.src = "Images/img"+ imageShown +".jpg";
console.log("Button clicked");
window.clearInterval(autoplay);
window.setInterval(autoplay, 5000);
}
My HTML:
<img src="Images/img1.jpg" id="picture" >
<div class="left_div"><img onClick="pic(-1)" class="left_click" src="Images/left.png"></div>
<div class="right_div"><img onClick="pic(+1)" class="right_click" src="Images/right.png"></div>
</div>
My CSS:
margin:0px;
}
#imageslider {
height:700px;
width:1000px;
margin: 50px auto;
position:absolute;
border-radius:4px;
overflow:hidden;
padding-right: 5000px;
padding-top: 1000px;
}
#picture {
height:750px;
width:1000px;
position:relative;
padding-top: 50px
}
.left_div {
height: 750px;
width: 150px;
position: absolute;
top: 250px;
left: 0px;
}
.right_div {
height: 750px;
width: 150px;
position: absolute;
top: 250px;
right: 0px;
}
.left_click {
height:50px;
width:50px;
position:absolute;
top:40%;
left:20px;
opacity:0;
transition: all .2s ease-in-out 0s;
}
.right_click {
height:50px;
width:50px;
position:absolute;
top:40%;
right:20px;
opacity:0;
transition: all .5s ease-in-out 0s;
}
.left_div:hover .left_click {
opacity:0.6;
}
.right_div:hover .right_click {
opacity:0.6;
}
.left:hover .left1
回答1:
You should use clearInterval as following:
clearInterval(autoplay);
or as
window.clearInterval(autoplay);
回答2:
I think that you might be trying to reset the interval incorrectly
http://www.w3schools.com/jsref/met_win_clearinterval.asp this gives an example of how to reset a function set to an interval in javascript
来源:https://stackoverflow.com/questions/28864879/reset-javascript-timer-for-image-slider