(function(){ var timer = null; hSlider(); function hSlider() { // 通过数组来控制slider内容切换 var imgadr = ['images/banner_2.jpg', 'images/banner_3.jpg', 'images/banner_1.jpg'], headArray = ['Second Heading', 'Third Heading','First Heading'], paraArray = ['First paragraph is awesome!', 'Second paragraph goes here!', 'Third paragraph for you' ], slider = document.getElementById('slider'), next = document.getElementById('prev'), prev = document.getElementById('next'), iNow = i = 0; // 获取slider作为画布,再通过改变数组来修改背景,标题和段落 function _bg(iNow) { slider.style.background = "url(\'" + imgadr[i] + "\') no-repeat center /cover"; document.getElementById('sliderHeader').innerHTML = headArray[i]; document.getElementById('sliderPara').innerHTML = paraArray[i]; } // 自动循环 timer = setInterval(function() { _bg(iNow); // 定时器每调动一次,自加一实现切换效果 i++; if (i == imgadr.length) i = 0; }, 3500); // 上一页 prev.onclick = function() { _bg(iNow); clearInterval(timer); i--; if (i == -1) i = imgadr.length - 1; } // 下一页 next.onclick = function() { _bg(iNow); clearInterval(timer); i++; if (i == imgadr.length) i = 0; // setInterval(timer); 没有效果 } } }
The reason is that I recently wanted to implement a full-screen carousel function, and then I queried a lot of information and referenced the codes of many websites, and then I found that most of them were obfuscated codes. I couldn’t understand them well. Then I made them myself. A primitive and simple carousel image.. Since the js foundation is not solid, there must be many problems. I hope dalao people can point out my mistakes.
The principle is to use the slider as a canvas. You can control the switching of background and paragraph text through an array, and set the timer. Loop, each time the array i is looped, it acts as a carousel. After the controller is clicked, "i" or "i--" controls the upper and lower pages. When clicked, I want to clear the timer, and then perform the effect of adding one to turn the page. Then add the timer back.
So here comes the question. I have stored the timer in a variable, so how do I call it again?
You can also put it into a function and call it again, but I don’t think it will work. not too good..?
Like this, I think setTimeout is easier to control than setInterval: