原生JavaScript实现简单的图片切换——DOM操作

在实际应用中,我们总是有进行图片切换操作的需求。图片切换有许多实现方法,有的用jQuery,有的借用框架等等。本文回归最初的最简单的实现。借用原生DOM操作实现定时切换图片。下面是代码:

html代码:

<div class="left" id="left">
    <img id="placeholder" src="./images/1.jpg" alt="1">
div>

JS代码:

function showPic1(n){
    if (!document.getElementById('placeholder')) return false;  //if there is not,not to continue   
    if (placeholder.nodeName != "IMG") return false;    //if there is not,not to continue
    if (n > 6) n = 1;
    document.getElementById('placeholder').setAttribute("src", "./images/"+n+".jpg");
    n++;
    setTimeout("showPic1("+n+")",4000);
}

window.onload = function(){
    setTimeout("showPic1(1)", 4000);
}

紫罗兰

你可能感兴趣的:(JavaScript,DOM,JavaScript)