for(){}和setInterval()不起作用

时间:2016-08-18 08:40:28

标签: javascript html

我想拍照5s改变下一张照片,但我无法做到这一点。

<div class="g-carousel" id="m-carousel">
    <a href="http://open.163.com/" class="pciture" target="_blank"><img src="imag/banner1.jpg" ></a>
    <a href="http://study.163.com/" class="pciture two" target="_blank" style="display:none"><img src="imag/banner2.jpg" ></a>
    <a href="http://www.icourse163.org/" class="pciture three" target="_blank" style="display:none"><img src="imag/banner3.jpg" ></a>
    <div class="button">
        <i class="checked"></i><i></i><i></i>
    </div>
</div>
<script type="text/javascript">
    function showpic() {
        var carousel = document.getElementById("m-carousel")
        var pciture = carousel.getElementsByClassName("pciture");
                for (var i=0 ; i < pciture.length; i++)
                    if (i>2) i=0;
                pciture[i].style.display="none";
                pciture[i+1].style.display="block";

        }
        window.onload=function function_name(argument) {
            setInterval("showpic()",5000);
        }   
</script>

3 个答案:

答案 0 :(得分:0)

你需要一个全球计数器:

var counter = 0;

function showpic() {
    var carousel = document.getElementById("m-carousel")
    var pciture = carousel.getElementsByClassName("pciture");

    // Hide all the pictures.
    for (var i=0 ; i < pciture.length; i++)
    {
        pciture[i].style.display="none";
    }

    // Show the picture based on the counter.
    pciture[counter].style.display="block";

    // Increment the counter ready for next time.
    counter++;

    // Check if the counter needs to loop back.
    if(counter >= pciture.length)
        counter = 0;
}

window.onload = function() {
    setInterval(showpic, 5000);
}   

Here is a working example

答案 1 :(得分:0)

工作jsfiddle

function showpic() {

        var carousel = document.getElementById("m-carousel");
        var carouselLength = carousel.getElementsByTagName("a").length;
        var pciture = carousel.getElementsByClassName("pciture");

        if (i>=carouselLength-1){
              pciture[i].style.display="none";
              i=0;
              pciture[i].style.display="block";
              i--;
         }else{
               pciture[i].style.display="none";
               pciture[i+1].style.display="block";
         }
         i++;           
        }
var i = 0;
setInterval(showpic,2000);

答案 2 :(得分:-3)

如果你改变

,也许会有所帮助
window.onload=function function_name(argument) {

window.onload=function(argument) {

希望有所帮助。

此致

P.S。长寿和繁荣: - )